码迷,mamicode.com
首页 > 编程语言 > 详细

(转)Springboot 中filter 注入对象

时间:2017-09-07 16:08:12      阅读:3408      评论:0      收藏:0      [点我收藏+]

标签:isp   auto   项目应用   replace   shm   closed   str   war   log   

问题:我建立一个全局拦截器,当然,这是测试的时候建立的,我把它命名为LogFilter,它继承了Filter,web应用启动的顺序是:listener->filter->servlet,而因为项目应用了springboot,所以我们项目启动时,先初始化listener,因此注解的bean会被初始化和注入;然后再来就filter的初始化,再接着才到我们的dispathServlet的初始化,因此,当我们需要在filter里注入一个注解的bean时,就会注入失败,因为filter初始化时,注解的bean还没初始化,没法注入。

那么,解决方法如下:

public FilterRegistrationBean filterProxy(){
   FilterRegistrationBean registrationBean = new FilterRegistrationBean();
   DelegatingFilterProxy httpBasicFilter = new DelegatingFilterProxy();
   registrationBean.setFilter(httpBasicFilter);
   Map<String,String> m = new HashMap<String,String>();
   m.put("targetBeanName","logFilter");
   m.put("targetFilterLifecycle","true");
   registrationBean.setInitParameters(m);
   List<String> urlPatterns = new ArrayList<String>();
   urlPatterns.add("/*");
   registrationBean.setUrlPatterns(urlPatterns);
   return registrationBean;
}
这样你就可以在LogFilter里面添加@Autowired下的bean了。 
public class LogFilter implements Filter {
    @Autowired
    @Qualifier(value="rztRabbitTemplate")
    private RabbitTemplate rabbitTemplate;
技术分享
@Bean
    public FilterRegistrationBean securityFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new DelegatingFilterProxy("SecurityFilter"));
        registration.addInitParameter("targetFilterLifecycle", "true");
        registration.addUrlPatterns("/*");
        registration.setOrder(102);
        return registration;
    }
    
    @Bean(name = "SecurityFilter")
    public SecurityFilter getSecurityFilter(){
        return new SecurityFilter();
    }
View Code
转自:http://blog.csdn.net/u013030980/article/details/55270818#comments

(转)Springboot 中filter 注入对象

标签:isp   auto   项目应用   replace   shm   closed   str   war   log   

原文地址:http://www.cnblogs.com/zhangmingcheng/p/7490015.html

(0)
(1)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!