views:

31

answers:

1

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"&gt;
    <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();
    }
}
+3  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.

jasonmp85
Yes, that's exactly what happens! We encountered this error in our own application and I wanted to share our experience in order to help someone else avoid our mistake.
Derek Mahar
By the way, thank you for explaining how a bean can obtain a reference to the application context in which it exists.
Derek Mahar