【发布时间】:2013-11-25 12:36:23
【问题描述】:
为了使用 Spring 编写集成测试,我想使用自定义类加载器加载测试应用程序上下文。原因是我们使用了 LoadTimeWeaver(org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver 或 org.springframework.instrument.classloading.ReflectiveLoadTimeWeaver)。不幸的是,默认的 Sun 类加载器不提供 LoadTimeWeaver 所需的 addTransformer 方法。通过在 vm 启动时使用带有 sprint-instrument.jar 的 javaagent,一切正常。
但这对于应该从不同机器、IDE 等运行的测试来说不是一个有效的选项。
我通过扩展 GenericXmlContextLoader 并为我的上下文加载器设置 SimpleInstrumentableClassLoader 尝试了一个简单的解决方案:
@ContextConfiguration(locations = { "classpath:/spring/_context.xml" }, loader = CustomApplicationContextLoader.class)
和
public class CustomApplicationContextLoader extends GenericXmlContextLoader {
@Override
protected void prepareContext(final GenericApplicationContext context) {
super.prepareContext(context);
context.setClassLoader(new SimpleInstrumentableClassLoader(ClassUtils.getDefaultClassLoader()));
}
}
这导致了类似的错误
Class [org.springframework.context.config.ContextNamespaceHandler] for namespace [http://www.springframework.org/schema/context] does not implement the [org.springframework.beans.factory.xml.NamespaceHandler] interface
可能是因为有些类是由默认类加载器加载的,而有些类是由检测类加载器加载的。
你有好的解决方案吗?
感谢您的帮助! 克里斯
【问题讨论】:
-
类路径中是否有所有 Spring jar?你有哪些?
-
虽然可能并非所有都是相关的:spring-context、spring-web、spring-jms、spring-test、spring-security-core、spring-security-web、spring-security-config、spring -data-jpa、spring-datacommons-cor、spring-tx、spring-webmvc、spring-instrument、spring-instrument-tomcat
标签: java spring integration-testing instrumentation