Monday, November 22, 2010

Easy access to Spring ApplicationContext in any non bean class

Checkout the following class

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

/**
 *
 * @author intesar
 * Simple bean class which implements ApplicationContextAware interface
  */
@Component
public class SpringApplicationContextFactory implements ApplicationContextAware {

    static ApplicationContext ctx;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ctx = applicationContext;
    }

    public static ApplicationContext getContext() {
        return ctx;
    }
}

When an ApplicationContext creates a class that implemetns the ApplicationContextAware interface, the class is provided with a reference to that ApplicationContext.

Note :    SpringApplicationContextFactory class can be declared using either Annotation or xml style

Usage : You might find this handy to access beans inside your Servlets, Portlets, or any other class which is not managed by Spring container

Sample Code :

SampleService service = (SampleService) SpringApplicationContextFactory.getContext().getBean("sampleServiceImpl");

Checkout Spring Documentation for more details