I am using Spring MVC for my web application. My beans are written in \"spring-servlet.xml
\" file
Now I have a class MyClass
and i want to
Step 1 :Inject following code in class
@Autowired
private ApplicationContext _applicationContext;
Step 2 : Write Getter & Setter
Step 3: define autowire="byType" in xml file in which bean is defined
Simply inject it..
@Autowired
private ApplicationContext appContext;
or implement this interface: ApplicationContextAware
There are many way to get application context in Spring application. Those are given bellow:
Via ApplicationContextAware:
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class AppContextProvider implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
Here setApplicationContext(ApplicationContext applicationContext)
method you will get the applicationContext
Via Autowired:
@Autowired
private ApplicationContext applicationContext;
Here @Autowired
keyword will provide the applicationContext.
For more info visit this thread
Thanks :)
In case you need to access the context from within a HttpServlet which itself is not instantiated by Spring (and therefore neither @Autowire nor ApplicationContextAware will work)...
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
or
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
As for some of the other replies, think twice before you do this:
new ClassPathXmlApplicationContext("..."); // are you sure?
...as this does not give you the current context, rather it creates another instance of it for you. Which means 1) significant chunk of memory and 2) beans are not shared among these two application contexts.
Even after adding @Autowire if your class is not a RestController or Configuration Class, the applicationContext object was coming as null. Tried Creating new class with below and it is working fine:
@Component
public class SpringContext implements ApplicationContextAware{
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws
BeansException {
this.applicationContext=applicationContext;
}
}
you can then implement a getter method in the same class as per your need like getting the Implemented class reference by:
applicationContext.getBean(String serviceName,Interface.Class)