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); } }
spring spring-mvc
Jigish
source share