概述
前言
在上一篇《在前后端分离的SpringBoot项目中集成Shiro权限框架》文章中,和大家分享了一下SpringBoot和Shiro的整合,但其实个人对Spring data JPA的理解也较为有限,公司的兄弟们长期使用MyBatis框架,想要转型学习成本较高,于是有了这一篇博文,将上一文中的架构与MyBatis Plus框架整合,现在分享出来希望能帮到习惯并想更优雅的使用MyBatis持久化框架的同学们。
本文中项目核心包如下:
SpringBoot1.5.9.RELEASE;
shiro-spring 1.4.0;
mybatis-plus 2.1.8;
开发工具为IDEA 2017 1.2,项目仍然是多模块项目,大体结构与前文所述相似,本文的重点在MyBatisPlus第三方框架与SpringBoot的整合配置,以及Druid连接池配置。
母项目pom.xml文件代码如下
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>spring-boot-mp-parent</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>demo-main</module>
<module>spring-boot-mp-shiro</module>
<module>spring-boot-mp-common</module>
<module>demo-biz-module1</module>
</modules>
<name>${project.artifactId}</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<java.version>1.8</java.version>
<spring-boot.version>1.5.9.RELEASE</spring-boot.version>
<mybatisplus-spring-boot-starter.version>1.0.5</mybatisplus-spring-boot-starter.version>
<mybatisplus.version>2.1.8</mybatisplus.version>
<fastjson.version>1.2.39</fastjson.version>
<shiro.version>1.4.0</shiro.version>
<shiro-redis.version>2.4.2.1-RELEASE</shiro-redis.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<!--在外部tomcat中发布故移除内置包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>${spring-boot.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<version>${spring-boot.version}</version>
<optional>true</optional>
</dependency>
<!-- mybatis-plus begin -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatisplus-spring-boot-starter</artifactId>
<version>${mybatisplus-spring-boot-starter.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>${mybatisplus.version}</version>
</dependency>
<!-- mybatis-plus end -->
<!-- JUnit test dependency -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring-boot.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.restassured</groupId>
<artifactId>rest-assured</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!--<dependency>-->
<!--<groupId>com.alibaba</groupId>-->
<!--<artifactId>druid</artifactId>-->
<!--<version>1.0.28</version>-->
<!--</dependency>-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>${shiro.version}</version>
</dependency>
</dependencies>
<build>
<finalName>spring-boot-mp-parent</finalName>
</build>
</project>
要注意的是,引入mybatis-plus包后无需再引入mybatis相关包,mybatis的版本由mybatis-plus维护。数据库驱动根据需要引入。
demo-main为本项目启动项目,结构如下图
pom.xml代码
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>spring-boot-mp-parent</artifactId>
<groupId>com.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo-main</artifactId>
<packaging>war</packaging>
<name>demo-main Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>com.example</groupId>
<artifactId>spring-boot-mp-shiro</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.example</groupId>
<artifactId>demo-biz-module1</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
<finalName>demo-main</finalName>
</build>
</project>
Application为入口类,代码如下
package com.example;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* Created by Administrator on 2018/1/4.
*/
@EnableTransactionManagement
@SpringBootApplication(exclude = {HibernateJpaAutoConfiguration.class},
scanBasePackages = {"com.example.main", "com.huitu.mp", "com.example.biz"})
public class Application {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Application.class);
app.setBannerMode(Banner.Mode.OFF);
app.run(args);
}
}
不使用JPA于是排除了HibernateJpaAutoConfiguration类,配置了希望扫描到的包路径。
config包中MyBatisPlusConfig类
package com.example.main.config;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Created by Administrator on 2018/1/15.
*/
@Configuration
public class MyBatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
配置了分页插件,也可以配置其他插件。
WebConfig类
package com.example.main.config;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.List;
/**
* Created by Administrator on 2018/1/4.
*/
@ControllerAdvice
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.serializationInclusion(JsonInclude.Include.NON_NULL);
ObjectMapper objectMapper = builder.build();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
objectMapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true);// 忽略 transient 修饰的属性
converters.add(new MappingJackson2HttpMessageConverter(objectMapper));
super.configureMessageConverters(converters);
}
}
从MyBatisPlus的demo中复制出的代码,用于全局处理SpringMVC的消息。initMethod包未使用忽略。
application.yml配置文件代码
spring:
http:
encoding:
charset: UTF-8
enabled: true
force: true
aop:
auto: true
#数据源
dataSource:
druid:
filters: mergeStat,wall,logback
initial-size: 5
max-active: 50
min-idle: 5
max-wait: 6000
validation-query: SELECT 'x'
test-on-borrow: true
test-on-return: true
test-while-idle: true
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
remove-abandoned: true
remove-abandoned-timeout: 1800
log-abandoned: true
web-stat-filter:
enabled: true
url-pattern: /*
exclusions: '*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*'
stat-view-servlet:
enabled: true
url-pattern: /druid/*
reset-enable: false
login-username: admin
login-password: 123456
#数据源1 业务数据
datasource1:
url: jdbc:mysql://localhost:3306/primary?characterEncoding=utf8
username: root
password:
driverClassName: com.mysql.jdbc.Driver
#shiro数据源,用于权限相关
shiroDataSource:
#MyISAM和InnoDB是两种最常用的数据库引擎,默认的引擎是MyISAM,性能最好,但不支持事务处理,只有InnoDB支持事务
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8
username: root
password:
driverClassName: com.mysql.jdbc.Driver
globalConfig1:
#主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
idType: 0
#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
fieldStrategy: 2
#驼峰下划线转换
dbColumnUnderline: true
#刷新mapper 调试神器
refreshMapper: true
globalConfigShrio:
#主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
idType: 3
#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
fieldStrategy: 2
#驼峰下划线转换
dbColumnUnderline: true
#刷新mapper 调试神器
refreshMapper: true
redis:
shiro:
host: 127.0.0.1
port: 6379
timeout: 0
password:
重点为dataSource的配置,其中druid的配置可以参考官网文档,globalConfig为MyBatisPlus的配置,不同数据源可以有对应的配置,也可以用相同配置。详见代码注释。
Shiro模块结构如下图
总体与上文相同,不同的地方在于MyShiroRealm类和ShiroDataSourceConfig类。
package com.huitu.mp.shiro.config;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.huitu.mp.shiro.entity.SysPermission;
import com.huitu.mp.shiro.entity.SysRole;
import com.huitu.mp.shiro.entity.UserInfo;
import com.huitu.mp.shiro.service.SysPermissionService;
import com.huitu.mp.shiro.service.SysRoleService;
import com.huitu.mp.shiro.service.UserInfoService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by Administrator on 2017/12/11.
* 自定义权限匹配和账号密码匹配
*/
public class MyShiroRealm extends AuthorizingRealm {
@Resource
private SysRoleService sysRoleService;
@Resource
private SysPermissionService sysPermissionService;
@Resource
private UserInfoService userInfoService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// System.out.println("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
UserInfo userInfo = (UserInfo) principals.getPrimaryPrincipal();
try {
List<SysRole> roles = sysRoleService.selectRoleByUser(userInfo);
for (SysRole role : roles) {
authorizationInfo.addRole(role.getRole());
}
List<SysPermission> sysPermissions = sysPermissionService.selectPermByUser(userInfo);
for (SysPermission perm : sysPermissions) {
authorizationInfo.addStringPermission(perm.getPermission());
}
} catch (Exception e) {
e.printStackTrace();
}
return authorizationInfo;
}
/*主要是用来进行身份认证的,也就是说验证用户输入的账号和密码是否正确。*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
throws AuthenticationException {
//获取用户的输入的账号.
String username = (String) token.getPrincipal();
// System.out.println(token.getCredentials());
//通过username从数据库中查找 User对象,如果找到,没找到.
//实际项目中,这里可以根据实际情况做缓存,如果不做,Shiro自己也是有时间间隔机制,2分钟内不会重复执行该方法
EntityWrapper<UserInfo> ew = new EntityWrapper<>();
ew.eq("username",username);
System.out.println(ew.getSqlSegment());
UserInfo userInfo = userInfoService.selectOne(ew);
// System.out.println("----->>userInfo="+userInfo);
if (userInfo == null) {
return null;
}
if (userInfo.getState() == 1) { //账户冻结
throw new LockedAccountException();
}
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
userInfo, //用户名
userInfo.getPassword(), //密码
ByteSource.Util.bytes(userInfo.getCredentialsSalt()),//salt=username+salt
getName() //realm name
);
return authenticationInfo;
}
}
MyShiroRealm类用于自定义权限匹配和账号密码匹配,持久化框架变了于是查询用户和权限的代码有些不同。
package com.huitu.mp.shiro.config;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
import java.sql.SQLException;
/**
* Created by Administrator on 2018/1/15.
*/
@Configuration
@MapperScan(basePackages = "com.huitu.mp.shiro.mapper", sqlSessionTemplateRef = "shiroSqlSessionTemplate")
public class ShiroDataSourceConfig {
@ConfigurationProperties(prefix = "spring.dataSource.druid.shiroDataSource")
@Bean(name = "shiroDataSource")
public DataSource shiroDataSource() throws SQLException {
return DruidDataSourceBuilder.create().build();
}
@Bean(name = "sessionFactoryShiro")
public SqlSessionFactory sessionFactoryShiro(@Qualifier(value = "shiroDataSource") DataSource dataSource,
PaginationInterceptor paginationInterceptor,
@Qualifier(value="globalConfigurationShiro")GlobalConfiguration globalConfiguration) throws Exception{
MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:shiroMapper/*.xml"));
Interceptor[] interceptors = new Interceptor[]{paginationInterceptor};
bean.setPlugins(interceptors);
bean.setGlobalConfig(globalConfiguration);
return bean.getObject();
}
@ConfigurationProperties(prefix = "globalConfigShrio")
@Bean(name="globalConfigurationShiro")
public GlobalConfiguration globalConfigurationShiro() {
return new GlobalConfiguration();
}
@Bean(name = "transactionManagerShiro")
public DataSourceTransactionManager dataSourceTransactionManager2(@Qualifier("shiroDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "shiroSqlSessionTemplate")
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("sessionFactoryShiro") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
ShiroDataSourceConfig类配置了数据源及事务相关配置,其中数据源使用druid数据源。
ShiroConfig类有些许变化,贴出代码
package com.huitu.mp.shiro.config;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Created by Administrator on 2017/12/11.
*/
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
// System.out.println("ShiroConfiguration.shirFilter()");
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
//注意过滤器配置顺序 不能颠倒
//配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了,登出后跳转配置的loginUrl
filterChainDefinitionMap.put("/logout", "logout");
// 配置不会被拦截的链接 顺序判断
filterChainDefinitionMap.put("/druid/**", "anon");
filterChainDefinitionMap.put("/static/**", "anon");
filterChainDefinitionMap.put("/ajaxLogin", "anon");
filterChainDefinitionMap.put("/login", "anon");
filterChainDefinitionMap.put("/**", "authc");
//配置shiro默认登录界面地址,前后端分离中登录界面跳转应由前端路由控制,后台仅返回json数据
shiroFilterFactoryBean.setLoginUrl("/unauth");
// 登录成功后要跳转的链接
// shiroFilterFactoryBean.setSuccessUrl("/index");
//未授权界面;
// shiroFilterFactoryBean.setUnauthorizedUrl("/403");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
/**
* 凭证匹配器
* (由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了
* )
*
* @return
*/
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher() {
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
hashedCredentialsMatcher.setHashAlgorithmName("md5");//散列算法:这里使用MD5算法;
hashedCredentialsMatcher.setHashIterations(2);//散列的次数,比如散列两次,相当于 md5(md5(""));
return hashedCredentialsMatcher;
}
@Bean
public MyShiroRealm myShiroRealm() {
MyShiroRealm myShiroRealm = new MyShiroRealm();
myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return myShiroRealm;
}
@Bean
public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(myShiroRealm());
// 自定义session管理 使用redis
securityManager.setSessionManager(sessionManager());
// 自定义缓存实现 使用redis
securityManager.setCacheManager(cacheManager());
return securityManager;
}
//自定义sessionManager
@Bean
public SessionManager sessionManager() {
MySessionManager mySessionManager = new MySessionManager();
mySessionManager.setSessionDAO(redisSessionDAO());
return mySessionManager;
}
/**
* 配置shiro redisManager
* <p>
* 使用的是shiro-redis开源插件
*
* @return
*/
@ConfigurationProperties(prefix = "redis.shiro")
public RedisManager redisManager() {
// RedisManager redisManager = new RedisManager();
// redisManager.setHost(host);
// redisManager.setPort(port);
// redisManager.setExpire(1800);// 配置缓存过期时间
// redisManager.setTimeout(timeout);
// redisManager.setPassword(password);
// return redisManager;
return new RedisManager();
}
/**
* cacheManager 缓存 redis实现
* <p>
* 使用的是shiro-redis开源插件
*
* @return
*/
@Bean
public RedisCacheManager cacheManager() {
RedisCacheManager redisCacheManager = new RedisCacheManager();
redisCacheManager.setRedisManager(redisManager());
return redisCacheManager;
}
/**
* RedisSessionDAO shiro sessionDao层的实现 通过redis
* <p>
* 使用的是shiro-redis开源插件
*/
@Bean
public RedisSessionDAO redisSessionDAO() {
RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
redisSessionDAO.setRedisManager(redisManager());
return redisSessionDAO;
}
/**
* 开启shiro aop注解支持.
* 使用代理方式;所以需要开启代码支持;
*
* @param securityManager
* @return
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
/**
* 注册全局异常处理
* @return
*/
@Bean(name = "exceptionHandler")
public HandlerExceptionResolver handlerExceptionResolver() {
return new MyExceptionHandler();
}
}
加入/druid/**路由无需登录的配置,可访问druid管理界面。
业务模块结构如下图
package com.example.biz.module1.config;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
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.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.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
import java.sql.SQLException;
/**
* Created by Administrator on 2018/1/15.
*/
@Configuration
@MapperScan(basePackages = "com.example.biz.module1.mapper",sqlSessionTemplateRef = "SqlSessionTemplateOne")
public class DataSourceOneConfig {
@ConfigurationProperties(prefix = "spring.dataSource.druid.datasource1")
@Bean(name = "datasource1")
@Primary
public DataSource dataSource1() throws SQLException {
return DruidDataSourceBuilder.create().build();
}
@Bean(name = "sessionFactory1")
@Primary
public SqlSessionFactory sqlSessionFactory1(@Qualifier(value = "datasource1") DataSource dataSource,
PaginationInterceptor paginationInterceptor,
@Qualifier(value = "globalConfiguration1") GlobalConfiguration globalConfiguration) throws Exception {
MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper1/*.xml"));
Interceptor[] interceptors = new Interceptor[]{paginationInterceptor};
bean.setPlugins(interceptors);
bean.setGlobalConfig(globalConfiguration);
return bean.getObject();
}
@ConfigurationProperties(prefix = "globalConfig1")
@Bean(name = "globalConfiguration1")
public GlobalConfiguration globalConfiguration1() {
return new GlobalConfiguration();
}
@Bean(name = "transactionManager1")
@Primary
public DataSourceTransactionManager dataSourceTransactionManager1(@Qualifier("datasource1") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "SqlSessionTemplateOne")
@Primary
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("sessionFactory1") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
DataSourceOneConfig类为业务模块数据源配置,同样使用druid数据源。
源码下载
参考
MybatisPlus Git
druid-spring-boot-starter Git
《spring boot(七):springboot+mybatis多数据源最简解决方案》
最后
以上就是怕孤单小馒头为你收集整理的SpringBoot+Shiro+MyBatisPlus搭建前后端分离的多模块项目前言参考的全部内容,希望文章能够帮你解决SpringBoot+Shiro+MyBatisPlus搭建前后端分离的多模块项目前言参考所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复