I am using Spring 3.0.3.
I would like to use the applicationContextProvider so I declared:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="applicationContextProvider" class="com.mycompany.util.ApplicationContextProvider"></bean>
<context:annotation-config/>
<tx:annotation-driven/>
</beans>
and my ApplicationContextProvider:
public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public void setApplicationContext(ApplicationContext _applicationContext) throws BeansException {
applicationContext = _applicationContext;
}
}
But the set is never being called!
and whenever I am using ApplicationContextProvider.getApplicationContext() returns null.
why is it?
Part of the problem may be that your getter is static. So its possible for you to call it before Spring has created an instance of ApplicationContextProvider.
You need to refer to the bean ‘applicationContextProvider’ that Spring has created for you when Spring is “ready” for you to use it. See Bean lifecycle
E.g. via a Junit test with your bean in ‘app-context.xml’ in src/test/resources
Then this gets a green bar for applicationContext being set.
Example output (don’t leave System.out in the test btw).
app-context.xml: