'Unable to use getConnection() from datasource

Here's my data source configuration:

@Bean(name = "database1")
@Primary
@ConfigurationProperties(prefix="database1.datasource")
public static DataSource primaryDataSource() {
    return DataSourceBuilder.create().build();
}

It's configured in a @Configuration class.

Here's how my application.properties looks like:

database1.datasource.jdbc-url=jdbc:mysql://localhost:3306/dbpms
database1.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
database1.datasource.username=root
database1.datasource.password=
spring.jpa.hibernate.ddl-auto=update
database1.datasource.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL8Dialect
database1.datasource.initialize=true;
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

This configuration is working as expected.

My issue comes when trying to get my connection from primaryDataSource():

primaryDataSource().getConnection;

That throws the following exception:

Exception in thread "Thread-5" java.lang.IllegalArgumentException: dataSource or dataSourceClassName or jdbcUrl is required.
at com.zaxxer.hikari.HikariConfig.validate(HikariConfig.java:1029)
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:109)

Why can't I invoke this method since my data source is working properly?



Solution 1:[1]

Remove static modifier from primaryDataSource() method declaration. It should look like this:

@Bean(name = "database1")
@Primary
@ConfigurationProperties(prefix="database1.datasource")
public DataSource primaryDataSource() {
    return DataSourceBuilder.create().build();
}

Solution 2:[2]

Additionally from JRichardsz answer, I believe that the correct variable name for the URL in application.properties is url, not jdbc-url.

Reference to that is in this documentation

https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html#application-properties.data.spring.datasource.url

Solution 3:[3]

If you want to access to any spring bean, you just need to autowire it to another bean, instead the invocation of method in configuration classes:

@Autowired
DataSource datasource;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 FARS
Solution 2
Solution 3 Duke