Differences between @Value annotation and environment API?

Are there any significant differences between injecting class fields with @Value annotation and finding them using the Spring API environment? Preferred over others (and under what circumstances)?

An example of using @Value:

class Config { @Value("${db.driverClassName}") private String driverClassName; @Value("${db.url}") private String url; @Value("${db.username}") private String username; @Value("${db.password}") private String password; @Bean public javax.sql.DataSource dataSource(){ PoolProperties poolProperties = new PoolProperties(); poolProperties.setDriverClassName(driverClassName); poolProperties.setUrl(url); poolProperties.setUsername(username); poolProperties.setPassword(password); return new org.apache.tomcat.jdbc.pool.DataSource(poolProperties); } } 

An example of using the environment API:

 class Config { @Autowired private Environment environment; @Bean public javax.sql.DataSource dataSource(){ PoolProperties poolProperties = new PoolProperties(); poolProperties.setDriverClassName(environment.getProperty("db.driverClassName")); poolProperties.setUrl(environment.getProperty("db.url")); poolProperties.setUsername(environment.getProperty("db.username")); poolProperties.setPassword(environment.getProperty("db.password")); return new org.apache.tomcat.jdbc.pool.DataSource(poolProperties); } } 
+7
spring spring-mvc
source share
1 answer

Environment is a combination of profiles and properties.

A profile is a named logical group of bean definitions that can be active or inactive depending on your environment. Beans can be assigned to a profile defined in XML or annotations. E.g. you can have one profile for development mode and another for production mode. You can find the docs for @Profile here to find out more about this.

To quote Environment docs:

The role of the Environment object with respect to profiles is to determine which profiles (if any) are currently active and which profiles (if any) should be active by default.

If you do not need access to this information, you must adhere to the replacement notation using the ${..} format and @Value annotations. Again, to quote the docs :

In most cases, however, at the Beans application level, you don’t need to interact directly with the environment, but instead you may need to replace the $ {...} property values ​​with a property placeholder configurator such as PropertySourcesPlaceholderConfigurer, which itself is EnvironmentAware and is registered by default with Spring 3.1 by default when using <context:property-placeholder/> .

So, we summarize:

  • With the Environement object Environement you can access profile related information. You cannot do this with @Value
  • Unless you need profile information (and you probably shouldn't), you should stick with @Value annotations.
+11
source share

All Articles