Reputation: 6537
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 access this class using spring bean
In the spring-servlet.xml
i have written following
<bean id="myClass" class="com.lynas.MyClass" />
Now i need to access this using ApplicationContext
ApplicationContext context = ??
So that I can do
MyClass myClass = (MyClass) context.getBean("myClass");
How to do this??
Upvotes: 131
Views: 391391
Reputation: 13
If your main()
method has SpringApplication.run()
method then you should remember ,it by default, returns the ApplicationContext object. See this.
Meaning,you can do this:
ApplicationContext context=SpringApplication.run(YourMainMethodClassName.class,args);
MyClass obj=(MyClass)context.getBean(MyClass.class);
Upvotes: 1
Reputation: 1324
Even better than having it with @Autowired is to let it be injected via constructor. Find some arguments pro constructor injection here
@Component
public class MyClass{
private final ApplicationContext applicationContext;
public MyClass(ApplicationContext applicationContext){
this.applicationContext = applicationContext;
}
//here will be your methods using the applicationcontext
}
Upvotes: 0
Reputation: 97
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)
Upvotes: 1
Reputation: 3613
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!!
Upvotes: 113
Reputation: 574
based on Vivek's answer, but I think the following would be better:
@Component("applicationContextProvider")
public class ApplicationContextProvider implements ApplicationContextAware {
private static class AplicationContextHolder{
private static final InnerContextResource CONTEXT_PROV = new InnerContextResource();
private AplicationContextHolder() {
super();
}
}
private static final class InnerContextResource {
private ApplicationContext context;
private InnerContextResource(){
super();
}
private void setContext(ApplicationContext context){
this.context = context;
}
}
public static ApplicationContext getApplicationContext() {
return AplicationContextHolder.CONTEXT_PROV.context;
}
@Override
public void setApplicationContext(ApplicationContext ac) {
AplicationContextHolder.CONTEXT_PROV.setContext(ac);
}
}
Writing from an instance method to a static field is a bad practice and dangerous if multiple instances are being manipulated.
Upvotes: 8
Reputation: 653
Add this to your code
@Autowired
private ApplicationContext _applicationContext;
//Add below line in your calling method
MyClass class = (MyClass) _applicationContext.getBean("myClass");
// Or you can simply use this, put the below code in your controller data member declaration part.
@Autowired
private MyClass myClass;
This will simply inject myClass into your application
Upvotes: 10
Reputation: 9281
If you're implementing a class that's not instantiated by Spring, like a JsonDeserializer you can use:
WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
MyClass myBean = context.getBean(MyClass.class);
Upvotes: 34
Reputation: 9
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
Upvotes: 0
Reputation: 6759
Another way is to inject applicationContext through servlet.
This is an example of how to inject dependencies when using Spring web services.
<servlet>
<servlet-name>my-soap-ws</servlet-name>
<servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
<init-param>
<param-name>transformWsdlLocations</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:my-applicationContext.xml</param-value>
</init-param>
<load-on-startup>5</load-on-startup>
</servlet>
Alternate way is to add application Context in your web.xml as shown below
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/classes/my-another-applicationContext.xml
classpath:my-second-context.xml
</param-value>
</context-param>
Basically you are trying to tell servlet that it should look for beans defined in these context files.
Upvotes: 0
Reputation: 4876
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.
Upvotes: 54
Reputation: 14408
Simply inject it..
@Autowired
private ApplicationContext appContext;
or implement this interface: ApplicationContextAware
Upvotes: 190