Thursday, October 29, 2009

Getting Spring POJOs from external Spring unaware systems

There are cases when one wants to instantiate POJOs from classes that are not Spring aware (like old EJBs).
In such circumstances, one needs to get the Spring application context and retrieve beans from the Spring container.

This is how you do it:

1. Create a class that provides the Spring application context from the container
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
* This class provides an application-wide access to the
* Spring ApplicationContext!
*
* Use AppContext.getApplicationContext() to get access
* to all Spring Beans.
*
*/
public class ApplicationContextProvider implements ApplicationContextAware
{
private static ApplicationContext ctx;

private ApplicationContextProvider(){}

public static ApplicationContext getApplicationContext()
{
return ctx;
}

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

2. Wire it in Spring

<bean id="contextApplicationContextProvider" class="com.yournamespace.ApplicationContextProvider"></bean>

3. Get a bean from any other class

SomeBean bean = (SomeBean)ApplicationContextProvider.getApplicationContext().getBean("someBean");

No comments:

Post a Comment