1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.tanpu.community.dao;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.tanpu.community.api.CommunityConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
/**
* created by xd on 2021/6/3
*/
@Configuration
@Slf4j
@MapperScan(basePackages = CommunityConstant.PACKAGE_BASE + ".dao.mapper.community", sqlSessionTemplateRef = "communitySqlSessionTemplate")
public class CommunityDataSourceConfig {
@ConfigurationProperties(prefix = "spring.datasource.community")
@Bean(name = "communityDataSource")
@Primary
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Primary
@Bean(name = "communitySqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier("communityDataSource") DataSource dataSource) throws Exception {
MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(
"classpath*:mapper/community/*.xml"));
return bean.getObject();
}
@Bean(name = "communityTransactionManager")
@Primary
public DataSourceTransactionManager communityTransactionManager(@Qualifier("communityDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "communitySqlSessionTemplate")
@Primary
public SqlSessionTemplate communitySqlSessionTemplate(@Qualifier("communitySqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
@Bean(name = "jdbcTemplate")
@Primary
public JdbcTemplate jdbcTemplate(@Qualifier("communityDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
@Bean(name = "jdbcTemplateNamed")
@Primary
public NamedParameterJdbcTemplate jdbcTemplateNamed(@Qualifier("communityDataSource") DataSource dataSource) {
return new NamedParameterJdbcTemplate(dataSource);
}
}