很多时候我们希望在拦截器或者过滤器中注入bean,但是springboot 默认是不能把相应的bean注入其中的,这个时候我们需要用以下的方式进行配置:
1,注入bean到拦截器中:
@Configuration public class WebMvcConfig extends WebMvcConfigurationSupport { @Bean public InterfaceAccessInterceptor interfaceAccessInterceptor(){ return new InterfaceAccessInterceptor(); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(interfaceAccessInterceptor()).order(1) .addPathPatterns("/**") .excludePathPatterns("/access/*****") .excludePathPatterns("/access/*****"); } }
请注意红色的部分
2,注入bean到filter
@Configuration public class FilterConfig { @Autowired private TestFilter testFilter; public FilterRegistrationBean filterRegistrationBean(){ FilterRegistrationBean filterRegistrationBean=new FilterRegistrationBean(); filterRegistrationBean.setFilter(testFilter); filterRegistrationBean.addUrlPatterns("/*****"); filterRegistrationBean.setName("testFilter"); return filterRegistrationBean; } }
@Component public class TestFilter implements Filter { @Autowired private TokenService tokenService; @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpServletRequest=(HttpServletRequest)servletRequest; tokenService.validateToken(httpServletRequest.getHeader("token")); filterChain.doFilter(servletRequest,servletResponse); } }
3, 还有一种最直接的办法:
BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
TokenService tokenService= (TokenService) factory.getBean("tokenService");
以上就是注入bean到拦截器,过滤器的解决办法
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Bean
public InterfaceAccessInterceptor interfaceAccessInterceptor(){
return new InterfaceAccessInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(interfaceAccessInterceptor()).order(1)
.addPathPatterns("/**")
.excludePathPatterns("/access/*****")
.excludePathPatterns("/access/*****");
}
}