Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

DataSource configuration

How to optimize setting data source fields when working with multiple datasources?

@Bean(name = ["dataSource"])
    fun dataSource(): DataSource {
        val dataSource = DriverManagerDataSource()
        dataSource.setDriverClassName(driverClassName)
        dataSource.url = url
        dataSource.username = username
        dataSource.password = password
        return dataSource
    }

Reduce boiler plate code shown above

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It is possible via application.yaml file and little DSL configuration.
application.yaml:

spring:
  datasource:
    first:
      driver-class-name: com.mysql.cj.jdbc.Driver
      password: #{DB_FIRST_PASSWORD}#
      username: #{DB_FIRST_USERNAME}#
      url: jdbc:mysql://#{DB_FIRST_HOST}#:#{DB_FIRST_PORT}#/#{DB_FIRST_NAME}#
      hikari:
        maximum-pool-size: 5
        minimum-idle: 5
    second:
      driver-class-name: org.postgresql.Driver
      password: #{DB_SECOND_PASSWORD}#
      username: #{DB_SECOND_USERNAME}#
      url: jdbc:postgresql://#{DB_SECOND_HOST}#:#{DB_SECOND_PORT}#/#{DB_SECOND_NAME}#
      hikari:
        maximum-pool-size: 3
        minimum-idle: 3

DatasourceConfiguration class

@Configuration
class DataSourceConfiguration {

    @get:Bean
    @get:ConfigurationProperties("spring.datasource.first")
    val firstDataSourceProperties = DataSourceProperties()

    @get:Bean
    @get:ConfigurationProperties("spring.datasource.second")
    val secondDataSourceProperties = DataSourceProperties()

    @Bean
    @Primary
    @ConfigurationProperties("spring.datasource.second.hikari") // GETS HIKARI CONFIGURATION
    fun firstDataSource(): DataSource =
        primaryDataSourceProperties
            .initializeDataSourceBuilder()
            .build()

    @Bean
    @ConfigurationProperties("spring.datasource.second.hikari") // GETS HIKARI CONFIGURATION
    fun secondDataSource(): DataSource =
        deliveryDataSourceProperties
            .initializeDataSourceBuilder()
            .build()

In addition, you can specify DataSource Hikari configuration using @ConfigurationProperties("spring.datasource.first.hikari") annotation

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading