How to configure mutiple DataSource with driver-class in Spring?

Viewed 271

Why is the driverclass missing in the following configuration?

spring.datasource.testdb.url=jdbc:mariadb://localhost/mytable
spring.datasource.testdb.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource.testdb.username=test
spring.datasource.testdb.password=test


@Configuration
public class DataSourceConfig {
    @ConfigurationProperties(prefix = "spring.datasource.testdb")
    @Primary
    public DataSource dataSourceTest() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public JdbcTemplate jdbcTemplateTest() {
        return new JdbcTemplate(dataSourceTest());
    }

    //secondary db config to follow
}

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>

    <dependency>
        <groupId>org.mariadb.jdbc</groupId>
        <artifactId>mariadb-java-client</artifactId>
    </dependency>
</dependencies>

Result:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured. Reason: Failed to determine a suitable driver class

This is strange, because I can even step into the org.mariadb.jdbc.Driver class, so it is clearly on classpath.

2 Answers

Looks like you just need to add the @Bean annotation to dataSourceTest().

@Bean
@ConfigurationProperties(prefix = "spring.datasource.testdb")
@Primary

Also, for the Hikari connection pool (which is the default connection pool), the url property is jdbc-url, not url. So change

spring.datasource.testdb.url=jdbc:mariadb://localhost/mytable

to

spring.datasource.testdb.jdbc-url=jdbc:mariadb://localhost/mytable

For more info, and other possible solutions see: After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

Hope this helps.

Are you sure that the properties file is being loaded correctly? The message clearly specifies that the url attribute was not specified, so apparently the spring.datasource.testdb.url=jdbc:mariadb://localhost/mytable line is not being read - the driver classpath has nothing to do with it.

The lines should be in an application.properties file by default, is that where you have them?

Related