[英]Why and in which cases spring load bean twice using different classLoaders?
Recently I visited an interview.最近我访问了一个采访。
I was asked:有人问我:
MyClass myClass =(MyClass) applicationContext.getBean("myClass");
throws ClassCastException
抛出ClassCastException
but applicationContext.getBean("myClass").getClass()
returns MyClass
.但applicationContext.getBean("myClass").getClass()
返回MyClass
。
I was surprised about the question.我对这个问题感到惊讶。 I could reply only that classes loaded by different classloaders.我只能回复由不同类加载器加载的类。
Yes different classloader will lead to this scenario.是的,不同的类加载器会导致这种情况。 This is not that common scenario however some application uses multiple classloaders (most common examples are containers and application servers).这不是常见的场景,但是某些应用程序使用多个类加载器(最常见的示例是容器和应用程序服务器)。 You can reproduce it你可以重现它
You can initialize spring application context by specifying URLClassLoader
您可以通过指定URLClassLoader
来初始化 spring 应用程序上下文
Have your class located at让你的班级位于
/home/jigar.joshi/foo/package/MyClass
and configure application context to use URLClassLoader like this并配置应用程序上下文以像这样使用 URLClassLoader
URL[] classURLs = { new URL("file:///home/jigar.joshi/foo") };
URLClassLoader urlClassLoader = new URLClassLoader(classURLs);
ApplicationContext context = new ClassPathXmlApplicationContext("spring/applicationContext.xml") {
protected void initBeanDefinitionReader(XmlBeanDefinitionReader reader) {
super.initBeanDefinitionReader(reader);
reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
reader.setBeanClassLoader(urlClassLoader);
setClassLoader(urlClassLoader);
}
};
MyClass m = context.getBean("MyClass");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.