从配置文件中获取数据源

Get a datasource from a config file

我正在开发 Spring 引导应用程序,并且正在编写数据库 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)
.....

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

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