配置文件:application.properties中进行相关配置,我们先配两个不同的数据源
#常用数据库配置
spring.datasource.primary.url=jdbc:mysql://localhost:3306/test01
spring.datasource.primary.username=root
spring.datasource.primary.password=root
spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driver
#非常用数据库的配置
spring.datasource.second.url=jdbc:mysql://localhost:3306/test02
spring.datasource.second.username=root
spring.datasource.second.password=root
spring.datasource.second.driver-class-name=com.mysql.jdbc.Driver
JdbcDataSource 的配置
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.Primary;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
// 表明这是一个配置文件,需要在启动时优先加载
@Configuration
public class JdbcDataSourceConfig {
/**
* 常用数据库配置
*/
@Bean(name = "primaryDataSource") // bean的名称,可以在注入的时候进行匹配
@ConfigurationProperties(prefix = "spring.datasource.primary") // 配置文件的前缀,会去主动读取此前缀开头配置的数据
@Primary // 默认加载
public DataSource primaryDataSource() {
// 这样我们就已经能读取常用数据库的配置了
return DataSourceBuilder.create().build();
}
@Bean(name = "primaryJdbcTemplate")
@Primary // 默认加载
public JdbcTemplate primaryJdbcTemplate(@Qualifier("primaryDataSource") DataSource primaryDataSource) {
// 这里使用@Qualifier的作用是为了指定注入那个dataSource,其实如果dataSource和jdbc在同一个类里的话,直接调用方法也行
// return new JdbcTemplate(primaryDataSource());
return new JdbcTemplate(primaryDataSource);
}
/**
* 非常用数据库配置
*/
@Bean(name = "secondDataSource") // bean的名称,可以在注入的时候进行匹配
@ConfigurationProperties(prefix = "spring.datasource.secoinnd") // 配置文件的前缀,会去主动读取此前缀开头配置的数据
public DataSource secondDataSource() {
// 这样我们就已经能读取非常用数据库的配置了
return DataSourceBuilder.create().build();
}
@Bean(name = "secondJdbcTemplate")
public JdbcTemplate secondJdbcTemplate(@Qualifier("secondDataSource") DataSource secondDataSource) {
return new JdbcTemplate(secondDataSource);
}
}
使用
@RestController
public class TestController {
// 两种引入方法
@Autowired
@Qualifier("primaryJdbcTemplate")
private JdbcTemplate jdbcTemplate;
// 两种引入方法
@Resource(name = "secondJdbcTemplate")
private JdbcTemplate jdbcTemplate2;
@GetMapping("/test1")
public List<Map<String, Object>> test() {
String sql = "select * from t_business_cq_assetassess";
List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
return maps;
}
@GetMapping("/test12")
public List<Map<String, Object>> test12() {
String sql = "select * from t_business_cq_assetassess";
List<Map<String, Object>> maps = jdbcTemplate2.queryForList(sql);
return maps;
}
}