Reputation: 397
I am trying to wire datasource to get properties from application(yml) file but the Datasourcebuilder is not reading those properties. I referred Stackoverflow as well as Spring Boot docs but could not see anything missing in my code. I am pasting the code below that uses Spring Boot 1.4.3.RELEASE
@SpringBootApplication
@EnableConfigurationProperties
@ComponentScan
public class MyApplication {
@Bean(name="dmDs")
@Primary
@ConfigurationProperties("spring.datasource")
public DataSource dmDataSource(){
return DataSourceBuilder.create().build();
}
@Bean
public String aBean(){
DataSource ds = dmDataSource(); // creates a datasource with URL, username and password empty.
return new String("");
}
The application config file is as shown below:
spring:
autoconfigure:
exclude:
- org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration
- org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
- org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration
- org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
profiles:
active: test
---
spring:
profiles: test
datasource:
url: jdbc:oracle:thin:SOME_URL
driver-class-name: oracle.jdbc.OracleDriver
password: test
username: test
datacollector:
datasource:
driver-class-name: oracle.jdbc.OracleDriver
url: jdbc:oracle:thin:@SOME_URL
username: user
password: pass
I see in the logs that the properties are read from the application.yml file
[main] o.s.c.e.PropertySourcesPropertyResolver : Found key 'spring.datasource.url' in [applicationConfig: [classpath:/application.yml]] with type [String]
[main] o.s.c.e.PropertySourcesPropertyResolver : Found key 'spring.datasource.driver-class-name' in [applicationConfig: [classpath:/application.yml]] with type [String]
[main] o.s.c.e.PropertySourcesPropertyResolver : Found key 'spring.datasource.password' in [applicationConfig: [classpath:/application.yml]] with type [String]
[main] o.s.c.e.PropertySourcesPropertyResolver : Found key 'spring.datasource.username' in [applicationConfig: [classpath:/application.yml]] with type [String]
JdbcTemplateAutoConfiguration matched:
- @ConditionalOnClass found required classes 'javax.sql.DataSource', 'org.springframework.jdbc.core.JdbcTemplate' (OnClassCondition)
- @ConditionalOnSingleCandidate (types: javax.sql.DataSource; SearchStrategy: all) found a primary bean from beans 'cipDs', 'dmDs' (OnBeanCondition)
I am running the application as shown below:
public static void main(String[] args){
SpringApplication.run(new Object[]{DecisionManagementApplication.class,ApplicationConfig.class}, args);
}
Upvotes: 2
Views: 4026
Reputation: 2427
If you want to use the bean Spring has created within its container you need to inject it, you can not use "new".
Try:
@Bean
@Autowired
public String aBean(final DataSource myDS)
{
return new String("Check myDS properties now");
}
Upvotes: 0