(转)Springboot 中filter 注入对象
问题:我建立一个全局拦截器,当然,这是测试的时候建立的,我把它命名为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(); }
转自:http://blog.csdn.net/u013030980/article/details/55270818#comments