What happens if a bean attempts to load the Spring application context in its constructor?
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 ClassPathXmlApplicati开发者_开发知识库onContext("applicationContext.xml");
public static void main(String[] args) {
A a = new A();
}
}
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.
精彩评论