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
Android Development for iOS Developers
Android development has greatly improved since the early days. Maybe you tried it out when Android development was done in Eclipse, emulators were slow and buggy, and Java was the required language. Things have changed […]
Add a custom object to your Liquibase diff
Adding a custom object to your liquibase diff is a pretty simple two step process. Create an implementation of DatabaseObject Create an implementation of SnapshotGenerator In my case I wanted to add tracking of Stored […]
Keeping Secrets Out of Terraform State
There are many instances where you will want to create resources via Terraform with secrets that you just don’t want anyone to see. These could be IAM credentials, certificates, RDS DB credentials, etc. One problem […]
Validating Terraform Plans using Open Policy Agent
When developing infrastructure as code using terraform, it can be difficult to test and validate changes without executing the code against a real environment. The feedback loop between writing a line of code and understanding […]