HandlerInterceptor里@Autowired对象为空的解决方法

That's because Spring isn't managing your PagePopulationInterceptor instance. You are creating it yourself in the below (拦截器内使用@Autowired时出现了null,这是由于你的spring对象注入时机在你的拦截器之后了)

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

@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注解了

方法多种多样,这里主要说明 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);
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章