知识点④:在 Interceptor 中使用 @autowired 自动注入

要使用 @autowired 自动注入,就需要知道该注解生效的条件

  1. @autowired 合适生效,即什么时候可以使用 @autowired 注解

    根据官方描述:You are free to use any of the standard Spring Framework techniques to define your beans and their injected dependencies.

    所以,我们只需要将我们的 Interceptor 注册为一个 bean ,就可以正常的使用@autowired注解了

  2. 方法多种多样,这里主要说明 springboot 中的使用方法:

    a. 方法一:通过给方法添加 @Bean 注解,返回一个 Interceptor 的 Bean,该 Interceptor 就可以正常的使用 @autowired 了

    例:

    拦截器类:

    public class PermissionInterceptor extends HandlerInterceptorAdapter {
    
    @Autowired
    private PortalUserService userService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
            if (!(handler instanceof HandlerMethod)) {
                return true;
            }
    
            //使用 userService
    
            return true;
        }
    
    }
    

    拦截器配置类:

    @Configuration
    public class WebMVCConfig extends WebMvcConfigurerAdapter {
    
        //在此处,将拦截器注册为一个 Bean 
        @Bean
        public PermissionInterceptor permissionInterceptor() {
            return new PermissionInterceptor();
        }
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(permissionInterceptor())
                    .addPathPatterns("/**")
                    .excludePathPatterns("/swagger-resources/**")
                    .excludePathPatterns("/v2/api-docs/**");
            super.addInterceptors(registry);
        }
    }
    

转载于:https://my.oschina.net/ss6/blog/1649706

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值