Friday, 3 March 2006

Getting a ServletConfig reference within Spring?

« Conference Call Strip Tease | Main | Geo-Blogging »

Let's say I've got the following in web.xml.

...
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/foo-applicationContext.xml</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
...

And let's say I've got a servlet with the following in its init method.

public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);

WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
_logger.debug(servletConfig.getInitParameter("foo"));
}

That call to getInitParameter works just fine here. But, what if I need access to the ServletConfig object from beans managed by Spring?

For some reason I'm not making the connection on how to make the connection and get the ServletConfig into the beans.

Scratching my head on what's probably a simple solution. Thanks in advance.

Update: It looks like the following Apache class from Jetspeed 2 does the trick.

import javax.servlet.ServletConfig;

import org.springframework.beans.factory.config.AbstractFactoryBean;

/**
* <p/>
* PreSetInstanceFactoryBean
* </p>
* <p/>
* <p/>
* </p>
*
* @author <a href="mailto:weaver@apache.org">Scott T. Weaver</a>
* @version $Id$
*/
public class ServletConfigFactoryBean extends AbstractFactoryBean {

private static ServletConfig servletConfig;

/**
* <p/>
* createInstance
* </p>
*
* @return
* @throws Exception
* @see org.springframework.beans.factory.config.AbstractFactoryBean#createInstance()
*/
protected final Object createInstance() throws Exception {
verifyState();
return servletConfig;
}

/**
* <p/>
* getObjectType
* </p>
*
* @return
* @see org.springframework.beans.factory.FactoryBean#getObjectType()
*/
public final Class getObjectType() {
return ServletConfig.class;
}

public final static void setServletConfig(ServletConfig servletConfig) {
ServletConfigFactoryBean.servletConfig = servletConfig;
}

protected final void verifyState() throws IllegalStateException {
if (servletConfig == null) {
throw new IllegalStateException("You invoke the ServletConfigFactoryBean.setServletConfig() " +
"method prior to attempting to get the ServletConfig.");
}
}
}

And then add the following in the Servlet.init method.

ServletConfigFactoryBean.setServletConfig(servletConfig);

That about does it.

Technorati Tags:

Posted by david at 9:55 AM in java ... just java

 

[Trackback URL for this entry]

Your comment:

(not displayed)
 
 
 

Live Comment Preview:

 
« First  « Prev   1 2 3 4 5   Next »  Last »
« March »
SunMonTueWedThuFriSat
   1234
567891011
12131415161718
19202122232425
262728293031