🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
>[info]当一个项目中有多个数据源时,可能就需要自定义不同数据源的 JdbcTemplate 了。 **1. application.yml** ```yml spring: datasource: username: root password: uhg</flEt3dff url: jdbc:mysql://localhost:3306/learndb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai driver-class-name: com.mysql.cj.jdbc.Driver type: com.zaxxer.hikari.HikariDataSource second: username: root password: uhg</flEt3dff url: jdbc:mysql://localhost:3306/common?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai driver-class-name: com.mysql.cj.jdbc.Driver ``` ![](https://img.kancloud.cn/91/96/9196e5482230943c502359c3bdd6f26a_1767x515.png) **2. 获取第二个数据源的配置** ```java @Setter @Getter @Component @ConfigurationProperties(prefix = "spring.datasource.second") public class SecondDataSourceProperties { private String username; private String password; private String url; private String driverClassName; } ``` **3. 自定义 JdbcTemplate** ```java @Configuration @RequiredArgsConstructor public class DataSourceConfig { final DataSourceProperties dataSourceProperties; final SecondDataSourceProperties secondDataSourceProperties; /** * 默认的数据源 */ public DataSource dataSource() { HikariConfig config = new HikariConfig(); config.setUsername(dataSourceProperties.getUsername()); config.setPassword(dataSourceProperties.getPassword()); config.setJdbcUrl(dataSourceProperties.getUrl()); config.setDriverClassName(dataSourceProperties.getDriverClassName()); return new HikariDataSource(config); } /** * 默认的JdbcTemplate */ @Bean @Primary public JdbcTemplate jdbcTemplate() { return new JdbcTemplate(dataSource()); } /** * 第二个数据源 */ public DataSource secondDataSource() { HikariConfig config = new HikariConfig(); config.setUsername(secondDataSourceProperties.getUsername()); config.setPassword(secondDataSourceProperties.getPassword()); config.setJdbcUrl(secondDataSourceProperties.getUrl()); config.setDriverClassName(secondDataSourceProperties.getDriverClassName()); return new HikariDataSource(config); } /** * 自定义JdbcTemplate */ @Bean("secondJdbcTemplate") public JdbcTemplate secondJdbcTemplate() { return new JdbcTemplate(secondDataSource()); } } ``` **4. 调用自定义JdbcTemplate** ```java @RestController @RequiredArgsConstructor public class DemoController { /** * 调用自定义的JdbcTemplate */ @Resource(name = "secondJdbcTemplate") final JdbcTemplate secondJdbcTemplate; /** * 调用默认的JdbcTemplate */ final JdbcTemplate jdbcTemplate; @GetMapping("/v1/student/getAll") public List<Map<String, Object>> getStuAll() { return secondJdbcTemplate.queryForList("select * from tb_student"); } @GetMapping("/v1/menu/getAll") public List<Map<String, Object>> getMenuAll() { return jdbcTemplate.queryForList("select * from menu"); } } ```