开发shiro的自定义realm时,抛出实体转换异常
@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; } 复制代码
其中 User user = (User) SecurityUtils.getSubject().getPrincipal();会抛出下面的异常
exception:java.lang.ClassCastException:cn.system.model.User cannot be cast to cn.system.model.User, 复制代码
项目启动时候加载项目当中的类所使用到的加载器是 org.springframework.boot.devtools.restart.classloader.RestartClassLoader , 这是因为之前在项目当中引入了 spring-boot-devtools 这个热部署包来提高效率。而我从 shiro session 取对象时候所用到的类加载器并不是这个,而是 sun.misc.Launcher.AppClassLoader ,从而导致我的类型的转换的异常。
restart.exclude.companycommonlibs=/mycorp-common-[//w-]+/.jar restart.include.projectcommon=/mycorp-myproj-[//w-]+/.jar 复制代码
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; } 复制代码