Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I inject a property value into a Spring Bean which was configured using annotations?

People also ask

How do you inject annotations in spring properties?

Injecting Properties Using @ValueUsing the @Value annotation, we can inject the values from the application. properties file into class fields in the Spring-managed bean GreetController . Using @Value allows you to set a default value if the requested one, for any reason, isn't available: @Value("${message.

Which annotation is used to inject property values into beans?

If we inject individual property values by using the @Value annotation or get the property values by using an Environment object, injecting multiple property values is cumbersome. Let's assume that we have to inject some property values to a UrlBuilder object.

What annotation can inject a property into Java code?

Using @Value With Maps We can also use the @Value annotation to inject a Map property.


You can do this in Spring 3 using EL support. Example:

@Value("#{systemProperties.databaseName}")
public void setDatabaseName(String dbName) { ... }

@Value("#{strategyBean.databaseKeyGenerator}")
public void setKeyGenerator(KeyGenerator kg) { ... }

systemProperties is an implicit object and strategyBean is a bean name.

One more example, which works when you want to grab a property from a Properties object. It also shows that you can apply @Value to fields:

@Value("#{myProperties['github.oauth.clientId']}")
private String githubOauthClientId;

Here is a blog post I wrote about this for a little more info.


Personally I love this new way in Spring 3.0 from the docs:

private @Value("${propertyName}") String propertyField;

No getters or setters!

With the properties being loaded via the config:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
      p:location="classpath:propertyFile.properties" name="propertiesBean"/>

To further my glee I can even control click on the EL expression in IntelliJ and it brings me to the property definition!

There's also the totally non xml version:

@PropertySource("classpath:propertyFile.properties")
public class AppConfig {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

There is a new annotation @Value in Spring 3.0.0M3. @Value support not only #{...} expressions but ${...} placeholders as well


<context:property-placeholder ... /> is the XML equivalent to the PropertyPlaceholderConfigurer.

Example: applicationContext.xml

<context:property-placeholder location="classpath:test.properties"/>  

Component class

 private @Value("${propertyName}") String propertyField;

Another alternative is to add the appProperties bean shown below:

<bean id="propertyConfigurer"   
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="/WEB-INF/app.properties" />
</bean> 


<bean id="appProperties" 
          class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="singleton" value="true"/>

        <property name="properties">
                <props>
                        <prop key="results.max">${results.max}</prop>
                </props>
        </property>
</bean>

When retrieved, this bean can be cast to a java.util.Properties which will contain a property named results.max whose value is read from app.properties. Again, this bean can be dependency injected (as an instance of java.util.Properties) into any class via the @Resource annotation.

Personally, I prefer this solution (to the other I proposed), as you can limit exactly which properties are exposed by appProperties, and don't need to read app.properties twice.


As mentioned @Value does the job and it is quite flexible as you can have spring EL in it.

Here are some examples, which could be helpful:

//Build and array from comma separated parameters 
//Like currency.codes.list=10,11,12,13
@Value("#{'${currency.codes.list}'.split(',')}") 
private List<String> currencyTypes;

Another to get a set from a list

//If you have a list of some objects like (List<BranchVO>) 
//and the BranchVO has areaCode,cityCode,...
//You can easily make a set or areaCodes as below
@Value("#{BranchList.![areaCode]}") 
private Set<String> areas;

You can also set values for primitive types.

@Value("${amount.limit}")
private int amountLimit;

You can call static methods:

@Value("#{T(foo.bar).isSecurityEnabled()}")
private boolean securityEnabled;

You can have logic

@Value("#{T(foo.bar).isSecurityEnabled() ? '${security.logo.path}' : '${default.logo.path}'}")
private String logoPath;