Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load spring context in an EJB based application

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

like image 370
dash27 Avatar asked Oct 25 '11 05:10

dash27


2 Answers

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.

like image 137
atrain Avatar answered Nov 02 '22 12:11

atrain


For EJB3, Spring recommends using an EJB3 Injection Interceptor. Basically you specify your Spring context using a ContextSingletonBeanFactoryLocator which entails creating your Spring context in a beanContextRef.xml in your classpath. Probably as part of your EAR. The SpringBeanAutowiringInterceptor injects your bean into your EJB.

like image 2
Bill Poitras Avatar answered Nov 02 '22 13:11

Bill Poitras