why can't I access ApplicationContext from ApplicationContextAware implemented bean

1.9k views Asked by At

I have a Spring JUnit tester class MySimpleTester:

@

RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:/spring/mySimpleConfig.xml"})
public class MySimpleTester {

@Before
    public void setUp() throws Exception {
        myAdapter = (MyAdapter) applicationContext.getBean("myAdapter");
    }

@test 
public void testGetSimpleList() {
        List<SimpleLink> simpleList = **myAdapter.getSimpleLinksList**();
}

... ...

In the adapter class I have:

public MyAdapter {
    public List<SimpleLink> getSimpleLinksList() {
        List<SimpleLink> simLinks = null;
        String environment = AppFactory.getPropertiesObj();

... ...

class AppFactory implements ApplicationContextAware {

    private static ApplicationContext context;

    public void setApplicationContext(ApplicationContext acontext) {
        context = acontext;
    }
    public getPropertiesObj() {
        return getAppContext().getBean("propertiesBean");
    }

I get NullPointerException and see that ApplicationContext is Null here.

However at the SpringJUnitTestRunner class MySimpleTester I could find the applicationContext to be initialized correctly. I am not including the mySimpleConfig.xml and included files. The method in MyAdapter class getSimpleLinksList() works perfectly fine from the web application when run in the application server, and the appcontext is obtained there.

Only from the Spring tester is it not able to reach the static application context AppFactory class, as it is called statically through AppFactory.getPropertiesObj(). I had the classpath set correctly as other test classes are executing.

2

There are 2 answers

1
Amit Bhati On

If you want to access the current ApplicationContext in MySimpleTester:-

public class MySimpleTester {

@Autowired
ApplicationContext applicationContext;

@Before
    public void setUp() throws Exception {
        myAdapter = (MyAdapter) applicationContext.getBean("myAdapter");
    }

@test 
public void testGetSimpleList() {
        List<SimpleLink> simpleList = **myAdapter.getSimpleLinksList**();
}
0
stillanovice On

I think it is happening as multiple application contexts are created. The AplliCationContext object is supposed to be singleton. But when from the static method we call the applicationContext again it is refering to altogether different confirguration. The ApplicationContext is not even initialised there.

This does not happen when the same module is called from Spring MVC webcontanier. It happens only when you try to use Spring tester classes RunWith(SpringJUnit4ClassRunner.class). I can pass the AppContext in the business method but I do not want to change the bsiness method signature. I found some threads in spring community with similar issue.