網頁

2020/4/14

Spring Boot datasource config jdbcUrl is required with driverClassName錯誤

今天在設定Spring Boot JDBC多資料庫的datasource配置時,啟動時發生jdbcUrl is required with driverClassName錯誤如下。

Caused by: java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName.
    at com.zaxxer.hikari.HikariConfig.validate(HikariConfig.java:951) ~[HikariCP-3.2.0.jar:?]
    at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:109) ~[HikariCP-3.2.0.jar:?]
    ...

問題原因出在application.properties中設定的datasource的key名稱。

下面是錯誤發生時的application.properties的datasource連線資訊。

application.properties

demo.datasource.url=jdbc:oracle:thin:@demo.caellrftl2c3.ap-northeast-1.rds.amazonaws.com:1521:demo
demo.datasource.username=abc
demo.datasource.password=123

下面是錯誤發生時的datasource配置類別DemoDataSourceConfig

DemoDataSourceConfig

@Configuration
public class DemoDataSourceConfig {
    
    @Primary
    @Bean(name = "demoDataSource")
    @ConfigurationProperties(prefix = "demo.datasource")
    public DataSource demoDataSource () {
        return DataSourceBuilder
            .create()
            .build();
    }
    ...
}

解決方式一是把指向資料庫的連線url的key應該要把結尾url改為jdbc-url

demo.datasource.jdbc-url=jdbc:oracle:thin:@demo.caellrftl2c3.ap-northeast-1.rds.amazonaws.com:1521:demo

若不想修改key的名稱,解決方式二是在DemoDataSourceConfig設定以下。

DemoDataSourceConfig

@Configuration
public class DemoDataSourceConfig {
    
    /** 此配置可將url轉換為jdbc-url */
    @Primary
    @Bean
    @ConfigurationProperties("demo.datasource")
    public DataSourceProperties dataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @ConfigurationProperties("demo.datasource.configuration")
    public HikariDataSource dataSource(DataSourceProperties properties) {
        return properties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
    }
} 

解決方式三,或直接在DemoDataSourceConfig手動設定jdbcUrl

DemoDataSourceConfig

@Configuration
public class DemoDataSourceConfig {

    @Value("${demo.datasource.url}") // <-- 注入applicatrion.properties的demo.datasource.url的值
    private String jdbcUrl;
    
    @Primary
    @Bean(name = "demoDataSource")
    @ConfigurationProperties(prefix = "demo.datasource")
    public DataSource demoDataSource () {
        return DataSourceBuilder
            .create()
            .url(jdbcUrl) // <-- 手動設定jdbcUrl
            .build();
    }
    ...
} 

沒有留言:

張貼留言