spring拦截器加载顺序
本地逻辑
创建拦截器-》加入配置-》spring注册拦截器
在使用注入时spring会自动去找容器的bean,但在配置类是首先加载的,@component注解加载在spring扫描注解时才加入,在注册拦截器的时候可能并没有加载到后面,所以会报错
所以在拦截器上加@component注解,然后在配置类使用@autowire是很容易产生加载spring加载顺序的问题的,可能ide运行的时候没报错,打包过后运行就报错了。
源代码
/**
* @description: 访问拦截器
* @author: zzy
* @create : 2020-08_28 16
**/
@Component
public class VisitorInterceptor implements HandlerInterceptor {
@Autowired
RedisTemplate redisTemplate;
@Autowired
IFeignSysVisitor iFeignSysVisitor;
private final String k_visitor="k_visitor_";
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
ValueOperations valueOperations = redisTemplate.opsForValue();
String date = DateUtil.format(new Date(), "yyyMMdd");
Long visitorCount = valueOperations.increment(k_visitor+date, 1);
if(visitorCount%20==0){
iFeignSysVisitor.save(new SysVisitorVo().setDate(date).setVisitorCount(visitorCount).setType(1));
}
return true;
}
}
@Autowired
VisitorInterceptor visitorInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authInterceptor).addPathPatterns("/**");
registry.addInterceptor(visitorInterceptor).addPathPatterns("/**");
}
这样容易产生加载顺序问题
使用 @DependsOn注解可以解决加载顺序问题
现代码
/**
* @description: 访问拦截器
* @author: zzy
* @create : 2020-08_28 16
**/
public class VisitorInterceptor implements HandlerInterceptor {
@Autowired
RedisTemplate redisTemplate;
@Autowired
IFeignSysVisitor iFeignSysVisitor;
private final String k_visitor="k_visitor_";
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
ValueOperations valueOperations = redisTemplate.opsForValue();
String date = DateUtil.format(new Date(), "yyyMMdd");
Long visitorCount = valueOperations.increment(k_visitor+date, 1);
if(visitorCount%20==0){
iFeignSysVisitor.save(new SysVisitorVo().setDate(date).setVisitorCount(visitorCount).setType(1));
}
return true;
}
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authInterceptor).addPathPatterns("/**");
registry.addInterceptor(getVisitorInterceptor()).addPathPatterns("/**");
}
@Bean
@DependsOn
public VisitorInterceptor getVisitorInterceptor(){
return new VisitorInterceptor();
}