我正在尝试连接数据源以从application(yml)文件获取属性,但Datasourcebuilder没有读取这些属性。我提到Stackoverflow以及Spring Boot docs,但在我的代码中看不到任何内容。 我粘贴下面的代码使用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("");
}
应用程序配置文件如下所示:
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
我在日志中看到属性是从application.yml文件中读取的
[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)
我正在运行应用程序,如下所示:
public static void main(String [] args){
SpringApplication.run(new Object[]{DecisionManagementApplication.class,ApplicationConfig.class}, args);
}
答案 0 :(得分:0)
如果你想使用Spring在容器中创建的bean,你需要注入它,你不能使用" new"。
尝试:
@Bean
@Autowired
public String aBean(final DataSource myDS)
{
return new String("Check myDS properties now");
}