Development environment
springboot-2.0.3, shiro-1.4, 开启 springboot-devtools
Due
Custom realm of developing shiro, an exception is thrown entity conversion
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
User user = (User) SecurityUtils.getSubject().getPrincipal();
String userName = user.getUsername();
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
// 获取用户角色集
List<Role> roleList = this.roleService.findUserRole(userName);
Set<String> roleSet = roleList.stream().map(Role::getRoleName).collect(Collectors.toSet());
simpleAuthorizationInfo.setRoles(roleSet);
// 获取用户权限集
List<Menu> permissionList = this.menuService.findUserPermissions(userName);
Set<String> permissionSet = permissionList.stream().map(Menu::getPerms).collect(Collectors.toSet());
simpleAuthorizationInfo.setStringPermissions(permissionSet);
return simpleAuthorizationInfo;
}
复制代码
Wherein User user = (User) SecurityUtils.getSubject () getPrincipal ();. Throws the following exception
exception:java.lang.ClassCastException:cn.system.model.User cannot be cast to cn.system.model.User,
复制代码
Cause Analysis
When the project started loading the project among the class loader used to be org.springframework.boot.devtools.restart.classloader.RestartClassLoader, because before the introduction of spring-boot-devtools this hot deployment package in which the project to improve the efficiency . And I take objects from shiro session when the class loader is not used to this, but sun.misc.Launcher.AppClassLoader, resulting in abnormal convert my type.
Solution
- Do not use spring-boot-devtools hot deployment
- Create a directory in the following resources META_INF folder, and then create spring-devtools.properties files, plus similar to the following configuration:
restart.exclude.companycommonlibs=/mycorp-common-[\\w-]+\.jar
restart.include.projectcommon=/mycorp-myproj-[\\w-]+\.jar
复制代码
- To remove the copy object properties, as follows:
public static Subject getSubjct() {
return SecurityUtils.getSubject();
}
public static User getUser() {
User user = null;
Object obj = getSubjct().getPrincipal();
if (StringUtils.isNotNull(obj)) {
user = new User();
BeanUtils.copyBeanProp(user, obj);
}
return user;
}
复制代码