Interceptor中使用@Autowired获取的值为null

当在自定义的AuthenticationInterceptor中使用@Autowired注入UserService时发现为null,原因是Interceptor未由Spring管理。解决方案是将Interceptor标记为@Component或使用@Bean创建,并在WebMvcConfig中注入并添加到拦截器链中。
摘要由CSDN通过智能技术生成

在自定义的HandlerInterceptor中使用@Autowired注入用户服务后,获取其值后发现为null

public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;
}

原因是在注册AuthenticationInterceptor时使用的是new关键字,没有将其交给Spring进行管理

 @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //  授权拦截
        registry.addInterceptor(new AuthenticationInterceptor()).addPathPatterns("/**")
                .excludePathPatterns("/login/**","/logout","/chat");
    }

那么我们只需要将我们的拦截器交给Spring进行管理

首先在AuthenticationInterceptor上加上@Component注解

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;
}

然后在我们的web配置类中注入这个对象,然后用这个对象替换之前用new关键字创建的对象即可

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Autowired
    private AuthenticationInterceptor authenticationInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //  授权拦截
        registry.addInterceptor(authenticationInterceptor).addPathPatterns("/**")
                .excludePathPatterns("/login/**","/logout","/chat");
    }
}

也可以使用@Bean注解,这样就不需要在AuthenticationInterceptor 上加@Component注解了

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Bean
    public AuthenticationInterceptor getAuthenticationInterceptor() {
        return new AuthenticationInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //  授权拦截
        registry.addInterceptor(getAuthenticationInterceptor()).addPathPatterns("/**")
                .excludePathPatterns("/login/**","/logout","/chat");
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值