Spring Boot中的属性.yml

时间:2018-10-25 06:08:21

标签: spring-boot

我已连接到数据库以读取数据。现在,每次上班或开发时,我都必须在班级中手动更改一行

// config.setJdbcUrl("jdbc:mysql://172.xxx.xxx.xxx:3306/asterisk");
// config.setJdbcUrl("jdbc:mysql://185.xxx.xxx.xxx:3306/asterisk");

我想将其添加到开发和生产的yaml文件中以使其自动化

然后执行以下操作,在我的yaml文件中添加它:

spring:
   ...
   datasource:
   ...
      asterisk:
        jdbc: jdbc:mysql://172.xxx.xxx.xxx:3306/asterisk  

在我的配置类中,以下内容:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = { "com.abalia.elser2.repository_asterisk" })
public class DatabaseAsteriskConfiguration {

private static HikariConfig config = new HikariConfig();
private static HikariDataSource ds;
private static String jdbc;

static {
    // config.setJdbcUrl("jdbc:mysql://172.xxx.xxx.xxx:3306/asterisk");
    // config.setJdbcUrl("jdbc:mysql://185.xxx.xxx.xxx:3306/asterisk");
    config.setJdbcUrl(jdbc);
    config.setUsername("xxxx");
    config.setPassword("xxxx");
    config.addDataSourceProperty("cachePrepStmts", "true");
    config.addDataSourceProperty("prepStmtCacheSize", "250");
    config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
    ds = new HikariDataSource(config);
}

public DatabaseAsteriskConfiguration(@Value("${spring.datasources.asterisk.jdbc") String jdbc) {
    DatabaseAsteriskConfiguration.jdbc = jdbc;
}

public static Connection getConnection() throws SQLException {
    return ds.getConnection();
}

}

错误:

java.lang.IllegalStateException: Cannot load configuration class: com.abalia.elser2.config.DatabaseAsteriskConfiguration
...
Caused by: java.lang.IllegalStateException: Unable to load cache item

1 个答案:

答案 0 :(得分:0)

当您从application.yaml调用某些配置时 您确保这是相同的配置密钥。我看了看,按键不同,在方括号中缺少了。 在您的application.yaml

spring:
   ...
   datasource:
   ...
      asterisk:
        jdbc: jdbc:mysql://172.xxx.xxx.xxx:3306/asterisk 

在您的方法上调用 spring.datasource.asterisk.jdbc 并放在方括号中。

@Value("${spring.datasource.asterisk.jdbc}")