springboot Jdbctemplate 多数据源

package com.lty.bus.conf;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

@Configuration
public class DataSourceConfig {

    @Primary
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.handan")
    DataSource handan() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.baoji")
    DataSource baoji() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    JdbcTemplate handanJdbc(@Qualifier("handan") DataSource ds) {
        return new JdbcTemplate(ds);
    }

    @Bean
    JdbcTemplate baojiJdbc(@Qualifier("baoji") DataSource ds) {
        return new JdbcTemplate(ds);
    }
}
package com.lty.bus.conf;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class JdbcTemplateConfig {

    @Autowired
    @Qualifier("handanJdbc")
    JdbcTemplate handanJdbc;

    @Autowired
    @Qualifier("baojiJdbc")
    JdbcTemplate baojiJdbc;

    public NamedParameterJdbcTemplate getJdbc(String cityCode){
        NamedParameterJdbcTemplate nameJdbc = new NamedParameterJdbcTemplate(handanJdbc);
        return nameJdbc;
    }


}
spring.datasource.handan.username=
spring.datasource.handan.password=
spring.datasource.handan.url=jdbc:postgresql://12.5.61.5:55432/handan_saas?characterEncoding=utf8&useSSL=true
spring.datasource.handan.driver-class-name=org.postgresql.Driver
spring.datasource.handan.type=com.alibaba.druid.pool.DruidDataSource

spring.datasource.baoji.username=
spring.datasource.baoji.password=
spring.datasource.baoji.url=jdbc:postgresql://2.1.2.9:5432/baoji?characterEncoding=utf8&useSSL=true
spring.datasource.baoji.driver-class-name=org.postgresql.Driver
spring.datasource.baoji.type=com.alibaba.druid.pool.DruidDataSource
        
            org.springframework.boot
            spring-boot-starter-jdbc
        

        
            com.alibaba
            druid-spring-boot-starter
            1.1.10
        

 

你可能感兴趣的:(springboot Jdbctemplate 多数据源)