需求描述: 链接多数据源进行增删改查
第一步:加载maven依赖(因为我用的是SQLserver和h2 数据库,因此导入如下包,若是其他数据库请自行在maven仓库中查找导入)
<!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/sqljdbc4 -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.0</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.1.0.jre8</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.199</version>
<scope>test</scope>
</dependency>
第二步:编写配置文件
在上述配置文件中,salve是SQLserver数据源,test是h2数据源,大家可根据此编写自己的数据源配置.
第三步:获取datasource 和jdbctemplate
@Configuration
public class DatasourceConfig {
@Bean(name = "primaryDataSource")
@Qualifier("primaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.test")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().type(DruidDataSource.class).build();
}
@Bean(name = "secondaryDataSource")
@Qualifier("secondaryDataSource")
@Primary
@ConfigurationProperties(prefix = "spring.datasource.salve")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().type(DruidDataSource.class).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);
}
}
上述代码中在获取datasource时,我指定了Alibaba的类型;此处一定要注意:如若不指定类型,则spring会自动去查找默认的数据源如下图:
当如下所有的数据源所需jar包没有在项目的类路径中,即引入以上四种数据源中任意一种数据源jar包到项目.若是没有指定类型,则会报错 Caused by: java.lang.IllegalStateException: No supported DataSource type found
此时只需要引入上图中所说的四个jar保重的任意一个到项目或引入Alibaba的druid数据源到项目,并指定类型为
第四步:执行增删改查