Accessing Spring beans from servlet filters and tags Accessing Spring beans from servlet filters and tags spring spring

Accessing Spring beans from servlet filters and tags


For filters - use Filter.init():

public void init(FilterConfig config) {    WebApplicationContext springContext =         WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());}

For tags - use TagSupport.pageContext (note that it's not available in SimpleTagSupport):

WebApplicationContext springContext =     WebApplicationContextUtils.getWebApplicationContext(pageContext.getServletContext());


you can use a DelegatingFilterProxy as mentioned in Spring documentation: http://static.springsource.org/spring-security/site/docs/3.0.x/reference/security-filter-chain.html#delegating-filter-proxy

You just have to declare your real Filter bean with the same bean name as the filter-name declared in web.xml:

web.xml:

    <filter>       <filter-name>SpringTestFilter</filter-name>       <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>    </filter>    <filter-mapping>       <filter-name>SpringTestFilter</filter-name>       <url-pattern>/*</url-pattern>    </filter-mapping>

applicationContext.xml:

    <bean id="SpringTestFilter" class="com.company.app.servlet.SpringTestFilter" />  


There are a couple ways to get it

  1. WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(getFilterCongig().getServletContext());

  2. WebApplicationContext springContext = RequestContextUtils.getWebApplicationContext(servletRequest)

then

springContext.getBean("myBeanId");