Spring has a mechanism called SingletonBeanFactoryLocator that can be used in places like EJB 2.0 to get the bean factory / application context in places where you cannot use dependency injection. There is a hook in the existing Spring ContextLoader that you are already using to take advantage of this functionality, although it is somewhat difficult to configure.
You need to share the contexts of your application with the parent / child relationship. The parent will contain the service level objects, and the child element consists of the specific material of the web layer.
Then you will need to add a couple of context parameters to your web.xml (for example, for the configuration location) to tell it to initialize the parent:
<context-param> <param-name>locatorFactorySelector</param-name> <param-value>classpath:beanRefFactory.xml</param-value> </context-param> <context-param> <param-name>parentContextKey</param-name> <param-value>beanRefFactory</param-value> </context-param>
locatorFactorySelector is a link to an xml file, BUT (I always confuse this), this will not point to the xml that defines your services. This is a bean xml definition that creates a bean application context. Then you reference this bean with the parentContextKey attribute.
So, for example, beanRefFactory.xml will contain:
<beans> <bean id="beanRefFactory" class="org.springframework.context.support.ClassPathXmlApplicationContext"> <constructor-arg> <list> <value>service-context.xml</value> </list> </constructor-arg> </bean> </beans>
In non-DIed related domain objects, you can go to the application context with this code:
BeanFactoryLocator locator = ContextSingletonBeanFactoryLocator.getInstance(locatorFactorySelector); BeanFactoryReference contextRef= locator.useBeanFactory(parentContextKey); ApplicatonContext context = (ApplicationContext) contextRef.getFactory();
More information about ContextSingletonBeanFactoryLocator can be found in this blog post . There is also a good description of using this approach in the EJB chapter in Java Development with the Spring Framework .
Jason gritman
source share