Spring using PropertySource with @Value

If you are using @Value with @PropertySource create a PropertySourcesPlaceholderConfigurer Bean which resolves ${…} placeholders within @Value annotations against the current Spring Environment and its set of PropertySources.

@Configuration
@PropertySource("file:conf/devdatabase.properties")
public class DataSourceConfigImpl implements DataSourceConfig{
	
	@Value("${DB_USERNAME}")
	private String devUserName;
	
	@Value("${DB_PASSWORD}")
	private String devPassword;
	
	@Value("${DB_URL}")
	private String devUrl;
	
	@Value("${DB_CLASSNAME}")
	private String driverClass;
		
	@Bean
	public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
		return new PropertySourcesPlaceholderConfigurer();
	}
       
    @Bean(name="devDataSource")
    public DataSource devDataSource() {
		try {
			 BasicDataSource dataSource = new BasicDataSource();
			 dataSource.setPassword(devPassword); 
			 dataSource.setUrl(devUrl); 
			 dataSource.setUsername(devUserName); 
			 dataSource.setDriverClassName(Class.forName(driverClass).getName());
			 return dataSource;
		} catch (Exception e) {
			logger.error("DataSourceConfigImpl.devDataSource(): " + e.getMessage());
		}
		return null;
    }

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: