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);
    }
}

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