我在 Spring Boot 1.4.0M3 上运行的应用程序中遇到一个奇怪的问题,该应用程序使用 Spring 缓存实现,其中提供程序是 Redis,我收到 classCastException 无法转换相同的对象
我使用 Mongodb 作为数据库,并且我有用户对象,其中包含延迟加载的角色对象列表,角色内部包含权限对象,如下所示
@Document
@Data
public class User implements Serializable{
private String passwordResetToken;
private boolean enabled = false;
@DBRef(lazy= true)
private List<Role> roleList;
}
我的角色DTO如下
@Data
@Document
public class Role implements Serializable{
private String roleName;
private String description;
@DBRef(lazy= true)
private List<Permission> permissions;
}
现在,在我的 Spring MVC 中,在加载所有角色时,我正在调用所有权限,并且由于这是重复操作,因此我考虑缓存结果并使用 Redis,并在加载角色值时收到以下异常。
raised java.lang.ClassCastException: com.learning.securedapp.domain.Permission cannot be cast to com.learning.securedapp.domain.Permission
帮助我克服这个错误。
我正在附上源代码 https://github.com/rajadileepkolli/springsecuredthymeleafapp到我的项目,我在第 91 行收到错误角色控制器.java https://github.com/rajadileepkolli/springsecuredthymeleafapp/blob/master/src/main/java/com/learning/securedapp/web/controllers/RoleController.java#L91
要在本地环境中复制,请登录到应用程序,然后单击权限菜单,然后单击角色菜单,现在在角色菜单中单击任何编辑图标。您将收到上述错误。
当您将 DevTools 与缓存一起使用时,您需要注意这个限制 http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-devtools-known-restart-limitations.
当对象被序列化到缓存中时,应用程序类加载器是C1。然后,在更改一些代码/配置后,devtools 会自动重新启动上下文并创建一个新的类加载器 (C2)。当您点击该缓存方法时,缓存抽象会在缓存中找到一个条目,并将其从存储中反序列化。如果缓存库不考虑上下文类加载器,则该对象将附加错误的类加载器(这解释了奇怪的异常A cannot be cast to A
).
TL;DR
如果缓存库不使用上下文类加载器,请勿使用 devtools 序列化类。或者把你的缓存库在应用程序类加载器中 http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-devtools-customizing-classload:
restart.include.yourcache=/my-cache-lib-[\\w-]+\.jar
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)