Aug 23, 2010

Gaining Access to the Spring Context in Non Spring Managed Classes

There are times where it’s not practical (or possible) to wire up your entire application into the Spring framework, but you still need a Spring loaded bean in order to perform a task.  JSP tags and legacy code are two such examples.   Here is a quick and easy way to get access to the application context.

First we create a class that has a dependency on the spring context.  The magic here is a combination of implementing ApplicationContextAware and defining the ApplicatonContext object as static.

package com.objectpartners.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringContext implements ApplicationContextAware {
  private static ApplicationContext context;

  public void setApplicationContext(ApplicationContext context) throws BeansException {
    this.context = context;
  }
  public static ApplicationContext getApplicationContext() {
    return context;
  }
}

Next,  we wire SpringContext into our spring container by defining it in our application-context.xml:

<bean id="springContext" class="com.objectpartners.util.SpringContext />

Now,  anywhere we need access to the spring context we can import SpringContext and call the getApplicationContext method like so:

import com.objectpartners.util.SpringContext;
class LegacyCode {
.
.

  SpringBean bean = (SpringBean)SpringContext.getApplicationContext.getBean("springBean");
.
.
}

Keep in mind that if there are multiple spring containers running on the JVM the static ApplicationContext object will be overwritten by the last container loaded so this approach may not work for you.

About the Author

jbaso profile.

Jon Baso

Sr. Consultant

Jon is a results-driven Software Developer with over a decade of experience in the full lifecycle development process involving analysis, design, development, deployment, testing, documentation, implementation and maintenance of application software. He has In-depth knowledge and experience of object oriented analysis and design specializing in JEE/Web Technologies including Spring, Hibernate, and JSF.

One thought on “Gaining Access to the Spring Context in Non Spring Managed Classes

  1. Andy H. says:

    Nicely written. I wasn’t aware of the multiple spring containers tip. Thanks!

  2. Pablo Karlsson says:

    Hi thanks for a good article. Im thinking about acessing a spring bean trough a Jruby script do you think this would be possible?

  3. Janarthan Sathiamurthy says:

    Super Article, exactly what I was looking for !

  4. Javid says:

    Simplest way of doing this.Thanks

  5. Daniel says:

    I’ve done this just for this scope

    https://danjee.github.io/hedgehog/

  6. Dave says:

    Great! That was exactly what I need !

  7. Gregory Bishop says:

    This is OK, but how can I avoid the XML?

    1. jbaso says:

      I haven’t tested this, but as long as you have component scanning enabled in your @Configuration file, you should be able to simply annotate the SpringContext bean with @Component

  8. cooligc says:

    Nice Article. I have a problem, my web application is legacy and I want to plug only one module as a Spring based project. How would I do that , could you help me by giving some approaches ?
    Tried Approach :
    In a static block , I have initiated the Spring factory . But, I need to have a shutdownHook to close the resources. I felt this approach not good as I am forcing the web container to initiate/close the Spring container.

  9. Gerviba says:

    I would change this.context to SpringContext.context

  10. Scott Ryan Corey says:

    Thank you very much! I have been searching for this exact thing for days!

  11. Techy says:

    Thank you so much!!!!

  12. Ashokumar says:

    Nice idea!

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Blog Posts
Using Conftest to Validate Configuration Files
Conftest is a utility within the Open Policy Agent ecosystem that helps simplify writing validation tests against configuration files. In a previous blog post, I wrote about using the Open Policy Agent utility directly to […]
SwiftGen with Image & Color Asset Catalogs
You might remember back in 2015 when iOS 9 was introduced, and we were finally given a way to manage all of our assets in one place with Asset Catalogs. A few years later, support […]
Tracking Original URL Through Authentication
If you read my other post about refreshing AWS tokens, then you probably have a use case for keeping track of the original requested resource while the user goes through authentication so you can route […]
Using Spring Beans in a Kafka Streams ExceptionHandler
There are many things to know before diving into Kafka Streams. If you haven’t already, check out these 5 things as a starting point. Bullet 2 mentions designing for exceptions. Ironically, this seems to be […]