从配置文件中获取数据源

时间:2016-11-17 23:27:51

标签: spring-boot datasource

我正在使用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)
.....

1 个答案:

答案 0 :(得分:0)

默认情况下,它会初始化从org.apache.tomcat.jdbc.pool.DataSource延伸的org.apache.tomcat.jdbc.pool.DataSourceProxy,如果您深入此课程,它会有' setUrl(字符串网址)',所以你需要使用

配置属性
datasource:
    driverClassName: org.postgresql.Driver
    url: jdbc:postgresql://10.26.80.192/myDB
    username: postgres
    password: