SpringBoot 注册拦截器方式及拦截器如何获取spring bean实例

SpringBoot 注册拦截器时,如果用New对象的方式的话,如下:

private void addTokenForMallInterceptor(InterceptorRegistry registry) {
InterceptorRegistration tokenInterceptor = registry.addInterceptor(new TokenInterceptor());
tokenInterceptor.addPathPatterns("/1");//默认需要一个拦截路径,防止路径校验为空时造成全部拦截
filterByIniProperties(tokenInterceptor, "token-mapping");
commonExclude(tokenInterceptor);
}

此种方式需要注册的拦截器依赖三方Bean注入的情况时,由于没有通过组件实例化,无法通过@Autowired 或@Resource等注解获取。

解决方案有两种:
1、注册拦截器时不用new的方式,也用注解组件注入
2、自己通过其它办法获取需要注入的Bean实例,如可以使用下面的方式获取

public class TokenInterceptor extends HandlerInterceptorAdapter {
private static final Logger LOGGER = LoggerFactory.getLogger(TokenInterceptor.class);
// private FeignProxy feignProxy;
private BaseCacheService baseCacheService;

public Boolean queryOrderAndDelete(HttpServletRequest request,Long platformId, String orderToken) {
// String result = this.cacheClient.getFromCache(platformId, orderToken);
if (baseCacheService == null) {
BeanFactory factory = WebApplicationContextUtils
.getRequiredWebApplicationContext(request.getServletContext());
baseCacheService = (BaseCacheService) factory.getBean("baseCacheServiceImpl");
}
。。。。。。
}


......
}

猜你喜欢

转载自www.cnblogs.com/xuzhujack/p/10924809.html
今日推荐