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

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


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