SqlServerDataSourceConfig.java 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package com.zcxk.config;
  2. import org.apache.ibatis.session.SqlSessionFactory;
  3. import org.mybatis.spring.SqlSessionFactoryBean;
  4. import org.mybatis.spring.SqlSessionTemplate;
  5. import org.mybatis.spring.annotation.MapperScan;
  6. import org.springframework.beans.factory.annotation.Qualifier;
  7. import org.springframework.boot.context.properties.ConfigurationProperties;
  8. import org.springframework.boot.jdbc.DataSourceBuilder;
  9. import org.springframework.context.annotation.Bean;
  10. import org.springframework.context.annotation.Configuration;
  11. import org.springframework.context.annotation.Primary;
  12. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
  13. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
  14. import javax.sql.DataSource;
  15. @Configuration
  16. @MapperScan(basePackages = "com.zcxk.dao.sqlserver", sqlSessionTemplateRef = "sqlServerSqlSessionTemplate")
  17. public class SqlServerDataSourceConfig {
  18. @Bean(name = "sqlServerDataSource")
  19. @ConfigurationProperties(prefix = "spring.datasource.sqlsever")
  20. @Primary
  21. public DataSource testDataSource() {
  22. return DataSourceBuilder.create().build();
  23. }
  24. @Bean(name = "sqlServerSqlSessionFactory")
  25. @Primary
  26. public SqlSessionFactory testSqlSessionFactory(@Qualifier("sqlServerDataSource") DataSource dataSource) throws Exception {
  27. SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
  28. bean.setDataSource(dataSource);
  29. bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:sqlServer/*.xml"));
  30. return bean.getObject();
  31. }
  32. @Bean(name = "sqlServerTransactionManager")
  33. @Primary
  34. public DataSourceTransactionManager testTransactionManager(@Qualifier("sqlServerDataSource") DataSource dataSource) {
  35. return new DataSourceTransactionManager(dataSource);
  36. }
  37. @Bean(name = "sqlServerSqlSessionTemplate")
  38. @Primary
  39. public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("sqlServerSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
  40. return new SqlSessionTemplate(sqlSessionFactory);
  41. }
  42. }