不考虑事务,需要事务的同学出门左转 ⬅️

该用法非常之不好,建议参考
SpringBoot 多数据源Starter

依赖

  1. <dependency>
  2. <groupId>org.mybatis.spring.boot</groupId>
  3. <artifactId>mybatis-spring-boot-starter</artifactId>
  4. <version>${version.mybatis-spring.verion}</version>
  5. </dependency>

配置

Properties 配置

  1. ##dao
  2. test1.url=jdbc:mysql://localhost:3306/test1?characterEncoding=UTF-8
  3. test1.user=root
  4. test1.pwd=root1234
  5. #---
  6. test2.url=jdbc:mysql://localhost:3306/test2?characterEncoding=UTF-8
  7. test2.user=root
  8. test2.pwd=root1234
  9. #---
  10. test3.url=jdbc:mysql://localhost.com:3306/test3?characterEncoding=UTF-8
  11. test3.user=root
  12. test3.pwd=root1234
  13. #---
  14. test4.url=jdbc:mysql://localhost:3306/test4?characterEncoding=UTF-8
  15. test4.user=root
  16. test4.pwd=root1234

Config 配置

test1 配置

  1. @Configuration
  2. @MapperScan(
  3. basePackages = {"com.example.test1.sql"},
  4. sqlSessionTemplateRef = "testSqlSessionTemplate"
  5. )
  6. public class Test1Config {
  7. @Value("${test1.url}")
  8. private String url;
  9. @Bean(name = "test1DataSource", initMethod = "init", destroyMethod = "close")
  10. public DruidDataSource dataSourceDms() {
  11. DruidDataSource druidDataSource = new DruidDataSource();
  12. druidDataSource.setUrl(url);
  13. druidDataSource.setUsername("root");
  14. druidDataSource.setPassword("root1234");
  15. druidDataSource.setMaxActive(10);
  16. druidDataSource.setInitialSize(1);
  17. druidDataSource.setTestOnBorrow(true);
  18. druidDataSource.setTestOnReturn(false);
  19. return druidDataSource;
  20. }
  21. @Bean("test1SqlSessionFactory")
  22. public SqlSessionFactory sessionFactory(@Qualifier("test1DataSource") DruidDataSource test1DataSource) throws Exception {
  23. SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
  24. sqlSessionFactoryBean.setDataSource(test1DataSource);
  25. sqlSessionFactoryBean.setMapperLocations(
  26. new PathMatchingResourcePatternResolver().getResources("classpath*:com/example/sql/test1dao/*Mapper.xml")
  27. );
  28. return sqlSessionFactoryBean.getObject();
  29. }
  30. @Bean("testSqlSessionTemplate")
  31. public SqlSessionTemplate sqlSessionTemplateDms(
  32. @Qualifier("test1SqlSessionFactory") SqlSessionFactory test1SqlSessionFactory) {
  33. return new SqlSessionTemplate(test1SqlSessionFactory);
  34. }
  35. }

其他的配置同test1,唯一需要主要的是扫描的包需要注意一下.