Reputation: 413
I am using Spring boot 2.0.1 with Hikari CP and want to use application properties to set Hikari datasource properties like Connection timeout, Maximum pool size etc but the username and password should be set at runtime. I tried below but when the datasource is created, it doesn't have the Connection timeout value I am trying to set.
Below is the code for datasource bean.
@Value("${spring.datasource.url}")
private String url;
@ConfigurationProperties(prefix = "spring.datasource.hikari")
@Bean
public DataSource dataSource() throws Exception {
//User name and password is fetched from some other data storage
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setJdbcUrl(url);
hikariConfig.setUsername(username);
hikariConfig.setPassword(password);
//The data source created here doesn't have connection timeout value
//set by me
return new HikariDataSource(hikariConfig);
}
Below is my application properties file
spring.datasource.url={Our DB URL}
spring.datasource.hikari.maximumPoolSize=100
spring.datasource.hikari.idleTimeout=30000
spring.datasource.hikari.poolName=SpringBootJPAHikariCP
spring.datasource.hikari.connectionTimeout=40000
spring.datasource.hikari.driver-class-
name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.hibernate.connection.provider_class=org.hibernate.hikaricp.internal.HikariCPConnectionProvider
I referred to below Spring documentation but it just talks about auto configuring properties like url and credentials (which worked) but not about connection timeout and idle timeout etc.
https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-configure-a-datasource
Please let me know if I am missing anything.
Upvotes: 3
Views: 9679
Reputation: 2073
@ConfigurationProperties(prefix = "spring.datasource.hikari")
@Bean
@Primary
public DataSource dataSource(String username,String password) {
return DataSourceBuilder.create().username(username).password(password).build();
}
and use these in yml/property file without giving username and password property.
spring:
profiles: dev
# Development database configuration
datasource.hikari:
driverClassName: oracle.jdbc.driver.OracleDriver
jdbcUrl: jdbc:oracle:thin:@url:1621:sid
type: com.zaxxer.hikari.HikariDataSource
connectionTimeout:40000
This will work. Let me know if it doesn't work for you.
Upvotes: 0