Here's my datasource 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 datasource is working properly?
CodePudding user response:
If you want to access to any spring bean, you just need to autowire it, instead the invokation of method in configuration classes:
@Autowire
Datasource datasource;
CodePudding user response:
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
CodePudding user response:
Simply 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();
}