Sharing the Spring application context from a WAR with EJBs
Picture the following scenario: You have an Enterprise Application Archive (EAR) which contains an EJB module and a WAR file. The web application uses a Spring application context and the same application context must be – for some reason – shared with your EJB. Using the beanRefContext.xml which points to the applicationContext.xml means that you will instantiate a new application context and have no access to the Spring environment of the web instance.
I used the following method:
- Create a @Singleton annotated EJB inside the EJB package which holds the global Spring application context which is shared between EJBs and WAR:
- Create a @ManagedBean with eager loading. This bean is loaded on startup of the web application. A @PostConstruct annotated method initialies the Spring context:
- Create a new EJB interceptor which inherits from SpringBeanAutowiringInterceptor. The interceptor references the @Singleton annotated EJB for looking up the bean factory: