shiro缓存管理时报错java.lang.ClassCastException: com.px.myshiro.domain.User cannot be cast to com.px.myshir

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_42614414/article/details/98501653

一、异常

java.lang.ClassCastException: com.px.myshiro.domain.User cannot be cast to com.px.myshiro.domain.User

问题

user不能转换为user,分明就是同一个user,怎么可能不能转换呢?需要转换吗?

分析

这主要发生在缓存服务时。主要原因是:**同一个类被不同的加载器加载**

当对象序列化到缓存中时,我们假设此时的类加载器为C1。
当代码发生改变时,会有另一个加载器,我们称它为C2。
当你调用缓存中的方法时,缓存抽象会在缓存中找到一个条目,并从缓存中进行反序列化,如果没有考虑上下文的类加载器,那么,这个对象就会被赋予错误的加载器。

解决方案一:如果你没有看懂我写的什么,或者你不需要热部署,可以在pom.xml文件中把spring-boot-devtools依赖注释了;

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
</dependency>

解决方案二:PropertyUtils.copyProperties(to,from);

public static UserPo getUser() {
      Object object = getSubjct().getPrincipal();
      UserPo userPo = new UserPo();
      try {
          PropertyUtils.copyProperties(userPo,object);
      } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
          e.printStackTrace();
      }
      return userPo;
}

二、如何在IDEA中设置热部署

pom.xml中添加

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-devtools</artifactId>
   <optional>true</optional>
</dependency>

<plugin>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-maven-plugin</artifactId>
   <configuration>
      <fork>true</fork>
   </configuration>
</plugin>    

在Eclipse中,默认自动编译,但在IDEA中,需要设置,具体步骤如下:
在这里插入图片描述
如果不行,Shift+Ctrl+Alt+/,选择Registry
在这里插入图片描述
进去之后,找到如下图所示的选项,打勾
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_42614414/article/details/98501653
今日推荐