How to use HikariCP in Spring Boot with two datasources in conjunction with Flyway

后端 未结 2 883
陌清茗
陌清茗 2021-02-03 23:50

I want to use HikariCP as JDBC connection pool in my Spring boot application. I have two datasources (MySQL database as the primary database and accessing those data through Hib

2条回答
  •  一向
    一向 (楼主)
    2021-02-04 00:48

    Thank you Andy for your fast and valuable answer ! You set me on the right track. After fiddling around, I found this configuration is working for me :

        @Bean
        @Primary
        @ConfigurationProperties("spring.datasource") 
      //@ConfigurationProperties("spring.datasource.hikari") can also be used, no difference
        public DataSourceProperties mySQLDataSourceProperties() {
            return new DataSourceProperties();
        }
    
        @Bean
        @Primary
        @ConfigurationProperties("spring.datasource.hikari")
        public DataSource mySQLDataSource() {
            return mySQLDataSourceProperties().initializeDataSourceBuilder().build();
        }
    
        @Bean
        @ConfigurationProperties(prefix = "spring.datasource.hikari")
        public HikariConfig hikariConfig() {
            return new HikariConfig();
        }
    
        @Bean
        public DataSource dataSource() {
            return new HikariDataSource(hikariConfig());
        }
    

    and I had to add these settings in the application.properties:

    # this is absolutely mandatory otherwise BeanInstantiationException in mySQLDataSource ! 
    spring.datasource.url=${JDBC_CONNECTION_STRING}
    
    spring.datasource.hikari.jdbc-url=${JDBC_CONNECTION_STRING}
    
    spring.datasource.hikari.username=user
    spring.datasource.hikari.password=pass
    

提交回复
热议问题