springboot实现多数据源加载
springboot一般情况下,正常的配置加载的是一个数据源。以下场景需要加载不同的数据源:有个模拟器,开发、测试、t1都在使用,不同环境的数据库不同,需要链接开发、测试、t1。
数据源1加载
package com.psbc.cpufp.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
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.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
@Configuration
@MapperScan(value = "com.psbc.cpufp.mapper.datasource1", sqlSessionFactoryRef = "sqlSessionFactory1")
public class DataSource1Config {
/**
* 创建druid数据库连接池
*/
@Bean(name = "dataSource1")
@ConfigurationProperties(prefix = "spring.datasource.druid.datasource1")
public DataSource dataSource1() {
return new DruidDataSource();
}
/**
* 创建链接工厂
*/
@Bean(name = "sqlSessionFactory1")
public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource1") DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath*:mapperOne/*.xml"));
return sqlSessionFactoryBean.getObject();
}
/**
* 创建template
*/
@Bean("sqlSessionTemplate1")
public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory1") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
数据源2加载
和数据源1加载一样