Friday, August 10, 2012

How to inject Spring properties using annotations?


I started to change a couple of projects from xml configuration to annotations and it wasn't trivial.
One of these items was the injection of properties using annotations.

First of all, we need a property configurer

<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>file:${configuration.path}/ng.properties</value>
</property>
</bean>
view raw gistfile1.xml hosted with ❤ by GitHub

The configuration file is a common property file.

application.title = My Application Title

In my case, I want to define a configuration bean, so I put in one place all the configurations. But you can use the same approach injecting the properties in your specific beans.

@Repository("ngConfiguration")
public class NGConfiguration {
@Value("${application.title}")
private String applicationTitle;
public String getApplicationTitle() {
return applicationTitle;
}
}
view raw gistfile1.java hosted with ❤ by GitHub
Hope it help you ...

No comments:

Post a Comment