定义一个filter
, 实现ApplicationContextAware
接口:
public class CacheFilter implements Filter, ApplicationContextAware {
private static ApplicationContext ctx; // 必须声明为static
@Override
public void init(FilterConfig config) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
CacheFilter.ctx = applicationContext; // 保存spring容器到static变量中
}
然后,在spring配置文件中配置该filter
,使之成为容器管理的bean:
<beans:bean id="cacheFilter" class="com.fh.taolijie.servlet.CacheFilter" />
最后,在web.xml
中声明过滤器:
<filter>
<filter-name>Cache Filter</filter-name>
<filter-class>com.fh.taolijie.servlet.CacheFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Cache Filter</filter-name>
<servlet-name>appServlet</servlet-name>
</filter-mapping>
这时,我们就可以在doFilter()
方法中直接通过ApplicationContext
检索需要的bean了:
StringRedisTemplate redis = (StringRedisTemplate)ctx.getBean("redisTemplate");
时间: 2024-10-11 22:49:30