Jon Baso

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.

Share this Post

Related Blog Posts

JVM

Integrating OpenSSO/OpenAM with Liferay Portal on Tomcat

August 16th, 2010

Integrate OpenSSO/OpenAM with Liferay Portal on Tomcat to achieve single-signon.

Steve Banks
JVM

Spring @PathVariable Head-slapper

August 12th, 2010

A simple oversight in the documentation and potentially unnecessary default in the Spring @PathVariable annotation can cause runtime trouble.

Object Partners
JVM

How Do Annotations Work?

August 6th, 2010

A quick trip through some examples of how to define, find, and ultimately use annotations to get work done on diverse classes.

Object Partners

About the author

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.