Answer: implement ApplicationContextAware. Well, it’s a yes, but only in the case when the servletContext is required after all the properties are set, but what to do if you need context property during instance initialization, before any of the properties have been set?
The solution is quite obvious - the servlet context needs to be injected in constructor. But how? I did not find a corresponding bean to do this so I decided to create a simple facility:
package com.anydoby;
import javax.servlet.ServletContext;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.context.WebApplicationContext;
public class ApplicationContextHelper implements ApplicationContextAware {
private WebApplicationContextctx;
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
this.ctx = (WebApplicationContext)ctx;
}
public ServletContext getContext() {
ServletContext servletContext = ctx.getServletContext();
return servletContext;
}
}This is the bean, which is being injected with the web application context. And here is the bean, which requires the servlet context:
public class SomeClass {
public SomeClass(ServletContext ctx) {
// do smth....
}
}and here goes the config stuff:
<bean class="SomeClass">
<constructor-arg>
<bean сlass="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject">
<bean сlass="com.anydoby.ApplicationContextHelper"></bean>
</property>
<property name="targetMethod" value="getContext"/>
</bean>
</constructor-arg>
</bean>that’s all :)
First published on the old anydoby.com blog on 2007-08-29.