一、准备好配置文件
二、目录结构
三、主数据源配置类
@Component
@Configuration
@MapperScan(basePackages= {"com.cmsz.falconjava.dao.primary"},sqlSessionFactoryRef="primarySqlSessionFactory")
public class PrimaryConfig {
@Bean(name="primaryDataSource")//注入到这个容器
@ConfigurationProperties(prefix="spring.datasource.primary")//表示取application.properties配置文件中的前缀
@Primary
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name="primarySqlSessionFactory")
@Primary
//@Qualifier的含义是告诉他使用哪个DataSource
public SqlSessionFactory testSqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource)
throws Exception {
SqlSessionFactoryBean bean=new SqlSessionFactoryBean();
bean.setTypeAliasesPackage("com.cmsz.falconjava.pojo");
bean.setDataSource(dataSource);
return bean.getObject();
}
@Bean(name="primaryTransactionManager")//配置事务
@Primary
public DataSourceTransactionManager testTransactionManager
(@Qualifier("primaryDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name="primarySqlSessionTemplate")
@Primary
public SqlSessionTemplate testSqlSessionTemplate
(@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
四、从数据源配置类
@Component
@Configuration
@MapperScan(basePackages= {"com.cmsz.falconjava.dao.secondary"},sqlSessionFactoryRef="secondarySqlSessionFactory")
public class SecondaryConfig {
@Bean(name="secondaryDataSource")//注入到这个容器
@ConfigurationProperties(prefix="spring.datasource.secondary")//表示取application.properties配置文件中的前缀
@Primary
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name="secondarySqlSessionFactory")
@Primary
//@Qualifier("primaryDataSource")//的含义是告诉他使用哪个DataSource
public SqlSessionFactory testSqlSessionFactory(@Qualifier("secondaryDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean=new SqlSessionFactoryBean();
bean.setTypeAliasesPackage("com.cmsz.falconjava.pojo");
bean.setDataSource(dataSource);
return bean.getObject();
}
@Bean(name="secondaryTransactionManager")//配置事务
@Primary
public DataSourceTransactionManager testTransactionManager(@Qualifier("secondaryDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name="secondarySqlSessionTemplate")
@Primary
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("secondarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
注意,配置类上面一定要加@Component注解,然后再启动类扫描配置类所在的包,不然启动会报错
我上面的配置类是没有xml文件的,如果是用的xml文件的,
在这个方法里面添加设置xml文件所在的路径
就是某个配置类扫描某个操作DAO层的接口或者xml文件,那么你这个配置类所读取的配置,就是该配置类扫描的接口或者xml文件所使用的数据源