What happens if a bean attempts to load the Spring application context in its constructor?

冷暖自知 提交于 2019-12-11 07:52:42

问题


Given the following Spring application context and class A, what happens when you run class A?

applicationContext.xml (in classpath):

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    <bean name="a" class="A"/>
</beans>

A.java:

class A {
    private ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

    public static void main(String[] args) {
        A a = new A();
    }
}

回答1:


Not to question your approach, but why is this necessary? If a bean wants a pointer to the application context it's a part of, it should implement ApplicationContextAware. You'll implement a setter and Spring will inject the app context into the bean.

Unless I'm mistaken, your sample code won't actually give that bean a pointer to its app context, it will start up a new app context using the same XML file as before. This will in turn create a new bean, which will start another app context, etc. — an infinite loop. Try out your code and see whether this happens.



来源:https://stackoverflow.com/questions/2923763/what-happens-if-a-bean-attempts-to-load-the-spring-application-context-in-its-co

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!