为什么以及在哪种情况下使用不同的classLoader两次加载bean? [英] Why and in which cases spring load bean twice using different classLoaders?

查看:74
本文介绍了为什么以及在哪种情况下使用不同的classLoader两次加载bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我访问了一次采访.

Recently I visited an interview.

有人问我:

MyClass myClass =(MyClass) applicationContext.getBean("myClass");

引发 ClassCastException

但是 applicationContext.getBean("myClass").getClass()返回 MyClass .

我对这个问题感到惊讶.我只能回答由不同的类加载器加载的类.

I was surprised about the question. I could reply only that classes loaded by different classloaders.

  1. 如何实现?
  2. 为什么Spring使用不同的类加载器?

推荐答案

是的,不同的类加载器将导致这种情况.这不是常见的情况,但是某些应用程序使用多个类加载器(最常见的示例是容器和应用程序服务器).您可以复制它

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

您可以通过指定 URLClassLoader

让您的班级位于

/home/jigar.joshi/foo/package/MyClass

并配置应用程序上下文以使用URLClassLoader这样

and configure application context to use URLClassLoader like this

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");

这篇关于为什么以及在哪种情况下使用不同的classLoader两次加载bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆