【问题标题】:Get a datasource from a config file从配置文件中获取数据源
【发布时间】:2016-11-17 23:27:51
【问题描述】:

我正在开发一个 Spring Boot 应用程序,并且正在编写一个数据库 HealthIndicator。我很难将 application.yml 中描述的数据源作为 Java 对象获取:

datasource:
    driverClassName: org.postgresql.Driver
    jdbcUrl: jdbc:postgresql://10.26.80.192/myDB
    username: postgres
    password: 

我试过的Java代码是:

@Component
public class DBHealthIndicator extends AbstractHealthIndicator {

    @Bean(name="getDataSource")  
    @ConfigurationProperties(prefix="datasource")  
    @Primary
    public DataSource getDataSource() {  
        return DataSourceBuilder.create().build();  
    }  

     public DBHealthIndicator() {
        super();
    }

    private boolean result = false;

    @Bean
    @Primary
    public DataSourceHealthIndicator dbHealthIndicator() {
         return new DataSourceHealthIndicator(getDataSource(), "SELECT * FROM USERS");
    }

   @Override
   protected void doHealthCheck(Health.Builder builder) throws Exception {

        Health h = dbHealthIndicator().health();
        Status status = h.getStatus();
        if (status != null && "DOWN".equals(status.getCode())) {
             result = false;
        } else {
             result = true;
        }
    }

    public boolean isResult() {
        return result;
    }

    public void setResult(boolean result) {
        this.result = result;
    }

}

我得到的错误是:

java.sql.SQLException: The url cannot be null
    at java.sql.DriverManager.getConnection(DriverManager.java:649)
    at java.sql.DriverManager.getConnection(DriverManager.java:208)
.....

【问题讨论】:

  • jdbcUrl 应该是url,不是吗?
  • 感谢您的回答。我没有写这个配置文件。我的一个同事做过,到目前为止,conf文件没有引起任何错误
  • 你试过改变它吗?该错误表明您的数据源没有 url - 该错误看起来与您的其余代码无关
  • jdbcUrl 是 Hikari 特有的属性。这里的其他人为您提供了正确的信息。当 Spring Boot 为你做这些时,我不明白你为什么要编写所有这些代码......
  • 我决定使用 Spring Boot 提供的 DataSourceHealthIndicator。谢谢大家的帮助和解释。

标签: spring-boot datasource


【解决方案1】:

默认情况下,它会初始化从org.apache.tomcat.jdbc.pool.DataSourceProxy扩展的org.apache.tomcat.jdbc.pool.DataSource,如果你深入这个类,它有'setUrl(String url)',所以你需要配置属性

datasource:
    driverClassName: org.postgresql.Driver
    url: jdbc:postgresql://10.26.80.192/myDB
    username: postgres
    password: 

【讨论】:

    猜你喜欢
    • 2013-01-19
    • 2013-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多