In the below Spring configuration class, I'm loading app.properties file via @PropertySource and constructing 2 different DBCP data sources using the configurations from the properties file.
Though everything works fine, I don't like declaring a variable for each configuration property with an annotation in order to construct the data source. I tried to autowire Environment class like this
@Autowired Environment env;
However, when env.getProperty() returns null. Is there a better way to do this?
@Configuration
@PropertySource("classpath:app.properties")
public class DAOConfig {
@Value( "${txn.dbhost}" ) private String txnDbHost;
@Value( "${txn.dbport}" ) private Integer txnDbPort;
@Value( "${txn.dbservice}" ) private String txnDbService;
@Value( "${txn.dbuser}" ) private String txnDbUser;
@Value( "${txn.dbpwd}" ) private String txnDbPwd;
@Value( "${rpt.dbhost}" ) private String rptDbHost;
@Value( "${rpt.dbport}" ) private Integer rptDbPort;
@Value( "${rpt.dbservice}" ) private String rptDbService;
@Value( "${rpt.dbuser}" ) private String rptDbUser;
@Value( "${rpt.dbpwd}" ) private String rptDbPwd;
@Bean(destroyMethod = "close")
public DataSource txnDataSource() {
return new DataSources.Builder()
.host(txnDbHost)
.port(txnDbPort)
.service(txnDbService)
.user(txnDbUser)
.pwd(txnDbPwd)
.build();
}
@Bean(destroyMethod = "close")
public DataSource rptDataSource() {
return new DataSources.Builder()
.host(rptDbHost)
.port(rptDbPort)
.service(rptDbService)
.user(rptDbUser)
.pwd(rptDbPwd)
.build();
}
}
Edit : I take that back about Environment.getProperty() not working. It indeed works. I was giving property names incorrectly. For those who don't want to use Spring Boot, you could autowire Environment as use it as follows:
@Configuration
@PropertySource("classpath:app.properties")
public class DAOConfig {
@Autowired Environment env;
@Bean(destroyMethod = "close")
public DataSource txnDataSource() {
return new DataSources.Builder()
.host(env.getProperty("txn.dbhost"))
.port(env.getProperty("txn.dbport"))
.service(env.getProperty("txn.dbservice"))
.user(env.getProperty("txn.dbuser"))
.pwd(env.getProperty("txn.dbpwd"))
.build();
}
}