通过Spring持久化数据时,不同的类加载器会导致ClassCastException [英] Different classloaders cause ClassCastException when persisting data via Spring
问题描述
我正在创建MVC Spring网络应用。
使用:Jetty(servlet容器),DataNucleus(dao平台),DB4O(嵌入式数据存储)。
I'm creating an MVC Spring webapp. Using: Jetty (servlet container), DataNucleus (dao platform), DB4O (embedded datastore).
当我持久存储对象时(在Spring内完成)控制器)使用DataNucleus的JDO,将其存储到数据库中。
When I persist an object (done from within a Spring Controller) using JDO from DataNucleus, it stores to the DB fine.
@PersistenceCapable
public class Test {
@Persistent
private String testString;
//getter-setters implemented
}
当我执行简单查询时对于我之前添加的对象,我在Test类上得到了 ClassCastException
(无法将 abcTest
转换为 abcTest
)。
When I do a simple query for the objects I previously added I get a ClassCastException
on my Test class (can't cast a.b.c.Test
to a.b.c.Test
).
JDO返回的Test的类加载器是(toString) [sun。 misc.Launcher$AppClassLoader@5acac268]
,在我将其持久保存到数据库之前,Test类的类加载器是 [WebAppClassLoader @ 1593275665]
The classloader of Test returned by JDO is (toString) [sun.misc.Launcher$AppClassLoader@5acac268]
, the classloader of the Test class before I persisted it to the DB is [WebAppClassLoader@1593275665]
我已经走了这么远,但是我真的不知道该怎么处理这样的类加载器问题,我从没在类加载器上花太多心思。任何方向都是有帮助的。
I've gotten this far, but I don't really know what to do with a classloader issue like this, I've never spent much thought on classloaders before. Any direction is helpful.
推荐答案
对于类强制转换异常,不需要两个不同版本的类。 由两个不同的类加载器加载时,即使是相同的类定义也被视为两个不同的类。在这里似乎是这种情况。
There doesn't need to be two different versions of the class for a class cast exception to appear. Even the same class definition is seen as two different classes when loaded by two distinct classloaders. Which seems to be the case here.
不幸的是,我我对您使用的平台不熟悉,因此我无法提供更具体的建议:尝试将包含您的 Test
类的罐子移到您的其他位置Web应用程序类路径,和/或重新配置Spring和Jetty类加载器,以便将 Test
的加载委派给同一父类加载器。
Unfortunately I am not familiar with the platforms you use, so I can't give more concrete advice than this: try to experiment with moving the jar containing your Test
class to different places on your web app classpath, and/or reconfiguring the Spring and Jetty classloaders so that both delegate the loading of Test
to the same parent classloader.
这篇关于通过Spring持久化数据时,不同的类加载器会导致ClassCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!