如果一个bean试图在它的构造函数中加载Spring应用程序上下文,会发生什么? [英] What happens if a bean attempts to load the Spring application context in its constructor?
问题描述
给定以下Spring应用程序上下文和类A,当您运行类A时会发生什么?
Given the following Spring application context and class A, what happens when you run class A?
applicationContext.xml(在类路径中):
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();
}
}
推荐答案
不质疑你的方法,但为什么这是必要的?如果一个bean想要一个指向应用程序上下文的指针,它是它的一部分,它应该实现 ApplicationContextAware 。你将实现一个setter,Spring会将应用上下文注入到bean中。
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.
除非我错了,你的示例代码实际上不会给这个bean一个指针到其应用上下文,它将使用与以前相同的XML文件启动一个新的应用上下文。这将反过来创建一个新的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.
这篇关于如果一个bean试图在它的构造函数中加载Spring应用程序上下文,会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!