spring加载拦截器找到多个bean

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();
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值