Load spring context in an EJB based application

dash27 picture dash27 · Oct 25, 2011 · Viewed 12.9k times · Source

The following is the situation :

I have a business layer, that is an EJB project. In fact, there is only one EJB that is created. This EJB is responsible to expose the service classes to other layers, that calls the EJB. I want to introduce spring (to use DI feature) in this layer.

My concern is, what is the best way to load the spring context in this business layer, so that the spring context does not get loaded again and again, whenever the EJB gets called ?

(In a Web project, there is an advantage rather to configure the spring context in contextLoaderListener, and it gets loaded once only when the application gets started)

I have thought of including spring in the same layer because :

  1. Configure the dependencies of all DAO and service classes and inject them wherever necessary.
  2. To use spring support for hibernate in the business layer.
  3. Ease of Unit testing, by injecting the properties into classes and simulating the same. Don't need to run the other layers again and again, to test my business classes/methods.
  4. To be able to use AOP (Aspect Oriented Programming) for Logging and method level auditing.

Kindly help me suggesting the best way, to load the spring context in an EJB project. I also want to know , if there are any alternatives if I can load the same in the app server (I am using Web sphere app server).

Thanks and Regards,

Jitendriya Dash

Answer

atrain picture atrain · Oct 25, 2011

Spring should be configured as part of your application in the normal way that you always set it up. Then you need to access the Spring beans from the EJB layer. To access (adapted from this post), create a Spring bean as follows:

@Component
public class SpringApplicationContext implements ApplicationContextAware {
    private static ApplicationContext CONTEXT;
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        CONTEXT = context;
    }
    public static Object getBean(String beanName) {
        return CONTEXT.getBean(beanName);
    }
}

Then, to call the bean in question from the legacy app:

SomeService someService = (SomeService)SpringApplicationContext.getBean("someServiceImpl");

The Spring context is initialized once, and your EJB layer can access at will.