I think this link demonstrates the best way to get application context anywhere, even in the non-bean class. I find it very useful. Hope its the same for you. The below is the abstract code of it
Create a new class ApplicationContextProvider.java
package com.java2novice.spring;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class ApplicationContextProvider implements ApplicationContextAware{
private static ApplicationContext context;
public static ApplicationContext getApplicationContext() {
return context;
}
@Override
public void setApplicationContext(ApplicationContext ac)
throws BeansException {
context = ac;
}
}
Add an entry in application-context.xml
<bean id="applicationContextProvider"
class="com.java2novice.spring.ApplicationContextProvider"/>
In annotations case (instead of application-context.xml)
@Component
public class ApplicationContextProvider implements ApplicationContextAware{
...
}
Get the context like this
TestBean tb = ApplicationContextProvider.getApplicationContext().getBean("testBean", TestBean.class);
Cheers!!