application.yml里的配置如下,注意要使用jdbc-url,否则会出现jdbcUrl is required with driverClassName:
spring:
datasource:
test1:
driver-class-name: xxx
jdbc-url: xxx
username: xxx
password: xxx
test2:
driver-class-name: xxx
jdbc-url: xxx
username: xxx
password: xxx
DataSourceConfig,一般就找个config文件夹放着:
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.boot.jdbc.DataSourceBuilder;
@Configuration
public class DataSourceConfig {
@Bean(name = "primaryDataSource")
@Qualifier("primaryDataSource")
@ConfigurationProperties(prefix="spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondaryDataSource")
@Qualifier("secondaryDataSource")
@Primary
@ConfigurationProperties(prefix="spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name="primaryJdbcTemplate")
public JdbcTemplate primaryJdbcTemplate (@Qualifier("primaryDataSource") DataSource dataSource ) {
return new JdbcTemplate(dataSource);
}
@Bean(name="secondaryJdbcTemplate")
public JdbcTemplate secondaryJdbcTemplate(@Qualifier("secondaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
在dao层,也就是实际从数据库查询数据的那一层,这样使用,在Qualifier后写需要的连接配置:
@Autowired
@Qualifier("primaryJdbcTemplate")
public JdbcTemplate jdbcTemplate;
特别注意一不小心会报错 jdbcUrl is required with driverClassName 。