【发布时间】: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。谢谢大家的帮助和解释。