[java] Spring get current ApplicationContext

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

This question is related to java spring spring-mvc servlets

The answer is


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


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

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


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
}

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)

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.


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


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


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.


ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-servlet.xml");

Then you can retrieve the bean:

MyClass myClass = (MyClass) context.getBean("myClass");

Reference: springbyexample.org


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to spring

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type

Examples related to spring-mvc

Two Page Login with Spring Security 3.2.x ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized The type WebMvcConfigurerAdapter is deprecated RestClientException: Could not extract response. no suitable HttpMessageConverter found Spring boot: Unable to start embedded Tomcat servlet container UnsatisfiedDependencyException: Error creating bean with name 8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

Examples related to servlets

Google Recaptcha v3 example demo Difference between request.getSession() and request.getSession(true) init-param and context-param java.lang.NoClassDefFoundError: org/json/JSONObject how to fix Cannot call sendRedirect() after the response has been committed? getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever? Create a simple Login page using eclipse and mysql Spring get current ApplicationContext insert data into database using servlet and jsp in eclipse What is WEB-INF used for in a Java EE web application?