Mar 17th, 2009, 12:06 PM
I have a web application, with an xml config file, beans defined in it, autowiring working, etc.
In a service I have 2 properties. One is normal and autowires fine. The other is static and although I want to initialize it from the context file, Spring tells me I may not autowire static properties.
I know that I can retrieve the object from the context with something like context.getBean("beanName"). But being a service class, it has no reference to the already loaded ApplicationContext nor ServletContext. I could load the context from XML all over with ClassPathXmlApplicationContext(locationOfXML) but that seems wasteful.
This seems like a very common problem, so there must be a well-known solution...
How do I get the currently loaded ApplicationContext if I don't have even a reference to the ServletContext?
Mar 17th, 2009, 03:42 PM
Never mind. Found the answer: Implement the ServletContextAware, and Spring will auto-magically call it... providing a ServletContext, from which you can obtain the ApplicationContext and get the bean.
One caviat is that it will happen only at the time the class implementing ServletContextAware is instantiated, so you have to code accordingly if your ultimate goal is to set a value for a static in that class.