首页 文章

Spring Boot数据源使用ConfigurationProperties注释,但未加载属性

提问于
浏览
1

我试图连接数据源以从应用程序(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);

}

1 回答

  • 0

    如果你想使用Spring在容器中创建的bean你需要注入它,你不能使用“new” .

    尝试:

    @Bean
    @Autowired
    public String aBean(final DataSource  myDS)
    {
        return new String("Check myDS properties now");
    }
    

相关问题