一般我们都是在controller层注入service那么如何在过滤器中注入service呢 一般使用过滤器在启动类中添加如下代码
1 @SpringBootApplication 2 @MapperScan("com.cmbchina.ccd.itpm.baffle.dao") 3 4 public class BaffleApplication extends SpringBootServletInitializer { 5 @Override 6 protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { 7 return builder.sources(BaffleApplication.class); 8 } 9 10 public static void main(String[] args) { 11 SpringApplication.run(BaffleApplication.class, args); 12 } 13 //配置过滤器 14 @Bean 15 public FilterRegistrationBean filterRegistrationBean(){ 16 FilterRegistrationBean filterFilterRegistrationBean = new FilterRegistrationBean(new UrlFilter()); 17 filterFilterRegistrationBean.addUrlPatterns("/*"); 18 return filterFilterRegistrationBean; 19 } 20 21 22 }
这样的话启动的时候就会加载这个过滤器 要是直接在过滤器中直接@Autowired 会出先空指针的我们可以采用下面的方法
1 @Component 2 public class UrlFilter implements Filter { 3 @Autowired 4 private UrlServicer urlServicer; 5 /* private static Logger logger= LoggerFactory.getLogger(UrlFilter .class);*/ 6 @Override 7 public void init(FilterConfig filterConfig) throws ServletException { 8 ServletContext sc = filterConfig.getServletContext(); 9 WebApplicationContext cxt = WebApplicationContextUtils.getWebApplicationContext(sc); 10 if(cxt != null && cxt.getBean(UrlServicer.class) != null && urlServicer == null) { 11 urlServicer =cxt.getBean(UrlServicer.class); 12 } 13 }
在过滤器加上@Component注解在init方法中初始化你要注入的service就可以了
感谢阅读