OSGi和JNI的类加载问题

时间:2012-07-08 10:44:53

标签: hibernate java-native-interface log4j classloader apache-felix

我有一个OSGi应用程序,可以从命令行启动并运行良好。但是,在生产环境中,此应用程序必须从用C编写的小程序启动。该程序检查许可证,执行其他操作并使用JNI与我的应用程序启动Java虚拟机。这样,我从log4j和hibernate得到了奇怪的错误(我启用了-verbose:class JVM标志):

[Loaded org.apache.log4j.Appender from reference:file:/opt/dc/lib/log4j-1.2.15.jar]
[Loaded org.apache.log4j.Appender from file:/opt/dc/lib/log4j-1.2.15.jar]
...
[Loaded org.apache.log4j.RollingFileAppender from file:/opt/dc/lib/log4j-1.2.15.jar]
log4j:ERROR A "org.apache.log4j.RollingFileAppender" object is not assignable to a     "org.apache.log4j.Appender" variable.
log4j:ERROR The class "org.apache.log4j.Appender" was loaded by 
log4j:ERROR [org.apache.felix.framework.BundleWiringImpl@eafb71] whereas object of type 
log4j:ERROR "org.apache.log4j.RollingFileAppender" was loaded by [sun.misc.Launcher$AppClassLoader@1cde100].
log4j:ERROR Could not instantiate appender named "ROLLINGFILE".
...
[Loaded org.dom4j.DocumentFactory from reference:file:/opt/dc/lib/dom4j-1.6.1.jar]
...
[Loaded org.dom4j.DocumentFactory from file:/opt/dc/lib/dom4j-1.6.1.jar]
...
java.lang.ClassCastException: org.dom4j.DocumentFactory cannot be cast to     org.dom4j.DocumentFactory
    at org.dom4j.DocumentFactory.getInstance(DocumentFactory.java:97)
    at org.dom4j.io.DOMReader.<init>(DOMReader.java:38)
    at org.hibernate.util.XMLHelper.createDOMReader(XMLHelper.java:69)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1615)
    at org.hibernate.cfg.AnnotationConfiguration.configure(AnnotationConfiguration.java:1218)

为什么这些类加载了两次?为什么有些从Felix加载,有些从Java类加载器加载?我怀疑一些本机代码在OSGi应用程序启动之前调用java(例如日志记录),而不是以某种方式重用那些加载的类导致ClassCastExceptions - 我如何证明或反驳这一点?

1 个答案:

答案 0 :(得分:0)

问题出在程序启动器内部。它将所有捆绑包添加到JVM的类路径中,尽管只需要Felix jar。