Spring get current ApplicationContext

JavaSpringSpring MvcServlets

Java Problem Overview


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??

Java Solutions


Solution 1 - Java

Simply inject it..

@Autowired
private ApplicationContext appContext;

or implement this interface: ApplicationContextAware

Solution 2 - Java

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!!

Solution 3 - Java

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.

Solution 4 - Java

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);

Solution 5 - Java

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

Solution 6 - Java

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.

Solution 7 - Java

There are many way to get application context in Spring application. Those are given bellow:

  1. 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

  1. Via Autowired:

     @Autowired
     private ApplicationContext applicationContext;
    

Here @Autowired keyword will provide the applicationContext.

For more info visit this thread

Thanks :)

Solution 8 - Java

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)

Solution 9 - Java

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

Solution 10 - Java

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.

Solution 11 - Java

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
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLynAsView Question on Stackoverflow
Solution 1 - JavagipinaniView Answer on Stackoverflow
Solution 2 - JavaVivekView Answer on Stackoverflow
Solution 3 - JavaJaroslav ZárubaView Answer on Stackoverflow
Solution 4 - JavarzymekView Answer on Stackoverflow
Solution 5 - JavaHitesh KumarView Answer on Stackoverflow
Solution 6 - JavaJuanView Answer on Stackoverflow
Solution 7 - JavaMd. Sajedul KarimView Answer on Stackoverflow
Solution 8 - JavaAman MalhotraView Answer on Stackoverflow
Solution 9 - JavaKamlesh PaunikarView Answer on Stackoverflow
Solution 10 - JavavsinghView Answer on Stackoverflow
Solution 11 - Javahecko84View Answer on Stackoverflow