今儿公司要搞个A库数据迁移到B库,但是表结构又不一样,有的数据还要查其他第三方服务。于是就搞了个多数据源DEMO,之前也弄过多数据源,读写分离操作使用的,采用AOP自定义注解控制。
spring: datasource: monit: driver-class-name: com.mysql.cj.jdbc.Driver jdbc-url: XXX username: root password: root pool: driver-class-name: com.mysql.cj.jdbc.Driver jdbc-url: XXX username: root password: root
这儿Springboot可能会报异常, com.mysql.cj.jdbc.Driver要选择2.1.5以上的Springboot父级,若选用2.0.0.RELEASE就用不了这个。
主要的还是在这儿:
目录建成这个样子,然后就是配置代码了...
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.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import javax.sql.DataSource; @Configuration @MapperScan(basePackages = "com.example.migration.mappers.monit", sqlSessionTemplateRef = "monitSessionTemplate") public class MonitConfig { //将这个对象放入Spring容器中 @Bean(name = "monitDataSource") //表示这个数据源是默认数据源 @Primary // 读取application.properties中的配置参数映射成为一个对象 // prefix表示参数的前缀 @ConfigurationProperties(prefix = "spring.datasource.monit") public DataSource getMonitDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "monitSessionFactory") // 表示这个数据源是默认数据源 @Primary //@Qualifier表示查找Spring容器中名字为test1DataSource的对象 public SqlSessionFactory monitSessionFactory(@Qualifier("monitDataSource") DataSource datasource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(datasource); return bean.getObject(); } @Bean("monitSessionTemplate") // 表示这个数据源是默认数据源 @Primary public SqlSessionTemplate monitSessionTemplate(@Qualifier("monitSessionFactory") SqlSessionFactory sessionfactory) { return new SqlSessionTemplate(sessionfactory); } }
代码如上,其他就正常的操作。