参考地址:https://blog.csdn.net/u012702547/article/details/88622445
1.pom.xml引包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.28</version> <scope>runtime</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency>
2.pplication.properties中配置数据源
spring.datasource.one.url=jdbc:mysql:///test01?useUnicode=true&characterEncoding=utf-8 spring.datasource.one.username=root spring.datasource.one.password=root spring.datasource.one.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.two.url=jdbc:mysql:///test02?useUnicode=true&characterEncoding=utf-8 spring.datasource.two.username=root spring.datasource.two.password=root spring.datasource.two.type=com.alibaba.druid.pool.DruidDataSource
3.注解配置多数据源
@Configuration public class DataSourceConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource.one") DataSource dsOne() { return DruidDataSourceBuilder.create().build(); } @Bean @ConfigurationProperties(prefix = "spring.datasource.two") DataSource dsTwo() { return DruidDataSourceBuilder.create().build(); } }
@Configuration public class JdbcTemplateConfig { @Bean JdbcTemplate jdbcTemplateOne(@Qualifier("dsOne") DataSource dsOne) { return new JdbcTemplate(dsOne); } @Bean JdbcTemplate jdbcTemplateTwo(@Qualifier("dsTwo") DataSource dsTwo) { return new JdbcTemplate(dsTwo); } }
4.测试
@RestController public class HelloController { @Autowired @Qualifier("jdbcTemplateOne") JdbcTemplate jdbcTemplateOne; @Resource(name = "jdbcTemplateTwo") JdbcTemplate jdbcTemplateTwo; @GetMapping("/user") public List<User> getAllUser() { List<User> list = jdbcTemplateOne.query("select * from t_user", new BeanPropertyRowMapper<>(User.class)); return list; } @GetMapping("/user2") public List<User> getAllUser2() { List<User> list = jdbcTemplateTwo.query("select * from t_user", new BeanPropertyRowMapper<>(User.class)); return list; } }