springboot 專案改進成多個數據源時遇到的問題
之前使用mybatis註解建立動態的sql語句,把相關jar包新增到springboot專案中使用,springboot中
@SpringBootApplication預設scanBasePackages是當前包
可以修改增加相關的多個包名
@SpringBootApplication(scanBasePackages = {"xyz.ccw.cloud"})
增加DataSourceUserConfig 配置類,Import(value = {SqlInterceptor.class})
@Configuration
@MapperScan(basePackages = {"xyz.ccw.cloud.messagecenter.dao" },sqlSessionTemplateRef = "userSqlSessionTemplate")
@Import(value = {SqlInterceptor.class})
public class DataSourceUserConfig {
@Value("${mybatis.mapperLocations}")
private String mybatisMapperLocations;
@Value("${mybatis.configLocations}")
private String mybatisConfigLocations;
@Autowired
private SqlInterceptor sqlInterceptor;
@Bean(name = "userDataSource")
@ConfigurationProperties(prefix = "spring.datasource.user")
public DataSource userDataSource() {
// return DataSourceBuilder.create().build();
return new DruidDataSource();
}
@Bean(name = "userSqlSessionFactory")
public SqlSessionFactory userSqlSessionFactory(@Qualifier("userDataSource") DataSource dataSource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
bean.setMapperLocations(resolver.getResources(mybatisMapperLocations));
bean.setConfigLocation(new ClassPathResource(mybatisConfigLocations));
bean.setTypeAliasesSuperType(BaseEntity.class);
bean.setPlugins(new Interceptor[]{sqlInterceptor});
Properties properties = new Properties();
properties.setProperty("dialect","mysql");
bean.setConfigurationProperties(properties);
return bean.getObject();
}
@Bean(name = "userTransactionManager")
public DataSourceTransactionManager userTransactionManager(@Qualifier("userDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "userSqlSessionTemplate")
public SqlSessionTemplate userSqlSessionTemplate(
@Qualifier("userSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}