May 29th, 2006, 08:29 PM
Accessing BeanFactory from bean/class not created by BeanFactory
I have a class X that is instantiated at different locations in the application code directly i.e. without using the BeanFactory. However in class X I would like to collaborate/use other beans created by the BeanFactory. I am unsure how I can achieve this. I can see the following potential approaches:
1. The classes that call the constructor of class X are spring beans and may be able to obtain a reference to the BeanFactory by implementing BeanFactoryAware and passing the reference on to the constructor of class X.
2. I create a bean that implements BeanFactoryAware and I inject this bean into class X in a static fashion using the MethodInvokingFactoryBean. Class X can then get the BeanFactory reference out by a method call on this bean.
I get the feeling there is a better way. I have found some references to BeanFactoryLocators but I am not sure how to get them to work given my code uses the DispatcherServlet and the contextConfigLocation servlet init param to specify the names of the bean definition xml files.
Any help appreciated. I am using Spring 1.2.7
May 29th, 2006, 08:56 PM
You may also
3. refactor the code to obtain instances of X from the BeanFactory
4. if you can access the HttpServletRequest or ServletContext from X, gain access to the application context using WebApplicationContextUtils.getWebApplicationContex t() or request.getAttribute(DispatcherServlet.WEB_APPLICA TION_CONTEXT_ATTRIBUTE)
May 29th, 2006, 08:59 PM
In Spring 2.0, you can access the request context from any class using RequestContextHolder.