问题
I can access Spring beans in my Servlets using
WebApplicationContext springContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
in the Servlet's init method.
I was wondering is there an equivalent of the WebApplicationContext for servlet filters?
Also, is it possible to access Spring beans in a tag class?
回答1:
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());
回答2:
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" />
回答3:
There are a couple ways to get it
WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(getFilterCongig().getServletContext());WebApplicationContext springContext = RequestContextUtils.getWebApplicationContext(servletRequest)
then
springContext.getBean("myBeanId");
回答4:
You can put all your beans as request attributes by using the ContextEsposingHttpServletRequest wrapper.
来源:https://stackoverflow.com/questions/2416671/accessing-spring-beans-from-servlet-filters-and-tags