Hi Sherihan,
Although it is a best practice to avoid writing container-aware code, there are certain circumstances in which this is necessary. Like you said, it can be a problem when Spring cannot be used to instantiate the class. An example of this is with EJBs, because the EJB container is responsible for creating them. Spring provides EJB-specific solutions for this issue.
I think your best bet might be to use either the SingletonBeanFactoryLocator or the ContextSingletonBeanFactoryLocator.
Here is a short summary from the Spring documentation: Glue code and the evil singleton.
Assuming you have a simple application with only one ApplicationContext (named "myApplicationContext.xml"), here is what I would suggest:
1) Create a new file, beanRefFactory.xml (which is the default name):
Code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="mainApplicationContext" lazy-init="true" class="org.springframework.context.support.ClassPathXmlApplicationContext">
<constructor-arg>
<value>myApplicationContext.xml</value>
</constructor-arg>
</bean>
</beans>
2) In the classes that require access to the ApplicationContext, add the following code:
Code:
public class SomeClassWhichNeedsAppContextAccess {
public static final String BEAN_FACTORY_KEY = "mainApplicationContext";
public Object getBean(String beanName) {
BeanFactoryLocator locator = SingletonBeanFactoryLocator.getInstance();
BeanFactoryReference bfr = locator.useBeanFactory(BEAN_FACTORY_KEY);
Object object = bfr.getFactory().getBean(beanName);
bfr.release();
return object;
}
}
Now this of course assumes that the classes in question can be modified. Can you provide more details as to your exact problem?
Hope this helps!
-Arthur Loder