在上一篇《在前后端分离的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文件代码如下
4.0.0
com.example
spring-boot-mp-parent
pom
1.0-SNAPSHOT
demo-main
spring-boot-mp-shiro
spring-boot-mp-common
demo-biz-module1
${project.artifactId}
http://maven.apache.org
UTF-8
UTF-8
1.8
1.8
1.8
1.5.9.RELEASE
1.0.5
2.1.8
1.2.39
1.4.0
2.4.2.1-RELEASE
org.springframework.boot
spring-boot-starter-web
${spring-boot.version}
org.springframework.boot
spring-boot-starter-tomcat
${spring-boot.version}
provided
org.springframework.boot
spring-boot-starter-aop
${spring-boot.version}
org.springframework.boot
spring-boot-devtools
${spring-boot.version}
true
com.baomidou
mybatisplus-spring-boot-starter
${mybatisplus-spring-boot-starter.version}
com.baomidou
mybatis-plus
${mybatisplus.version}
org.springframework.boot
spring-boot-starter-test
${spring-boot.version}
test
com.jayway.restassured
rest-assured
2.9.0
com.alibaba
fastjson
${fastjson.version}
com.alibaba
druid-spring-boot-starter
1.1.6
mysql
mysql-connector-java
5.1.39
runtime
com.oracle
ojdbc6
11.2
org.apache.velocity
velocity
1.7
test
org.apache.shiro
shiro-spring
${shiro.version}
spring-boot-mp-parent
要注意的是,引入mybatis-plus包后无需再引入mybatis相关包,mybatis的版本由mybatis-plus维护。数据库驱动根据需要引入。
demo-main为本项目启动项目,结构如下图
pom.xml代码
spring-boot-mp-parent
com.example
1.0-SNAPSHOT
4.0.0
com.example
demo-main
war
demo-main Maven Webapp
http://maven.apache.org
com.example
spring-boot-mp-shiro
1.0-SNAPSHOT
com.example
demo-biz-module1
1.0-SNAPSHOT
org.springframework.boot
spring-boot-maven-plugin
true
org.apache.maven.plugins
maven-compiler-plugin
${java.version}
demo-main
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> 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 roles = sysRoleService.selectRoleByUser(userInfo);
for (SysRole role : roles) {
authorizationInfo.addRole(role.getRole());
}
List 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 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 filterChainDefinitionMap = new LinkedHashMap();
//注意过滤器配置顺序 不能颠倒
//配置退出 过滤器,其中的具体的退出代码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
*
* 使用的是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实现
*
* 使用的是shiro-redis开源插件
*
* @return
*/
@Bean
public RedisCacheManager cacheManager() {
RedisCacheManager redisCacheManager = new RedisCacheManager();
redisCacheManager.setRedisManager(redisManager());
return redisCacheManager;
}
/**
* RedisSessionDAO shiro sessionDao层的实现 通过redis
*
* 使用的是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多数据源最简解决方案》