Spring boot 的 HandlerInterceptorAdapter 無法注入 @Service ,得到 NullPointerException 的錯誤
Getting a NullPointerException when trying to @Autowire
my @Service
in Interceptor,在 Spring Boot 利用 Filter 與 htmlcompressor 最小化 HTML 網頁Size,中有說明了 攔截器 ( Interceptor ) 與篩選器 ( Filter ) 的差異,當在 Interceptor 中注入 Service ,使用中卻得到 NullPointerException 的錯誤,這有可能的原因是,這個 Interceptor 在註冊時,它並不是一個 @Bean
,程式碼如下:
/** * 註冊 Interceptor */ @Override public void addInterceptors(InterceptorRegistry registry) { SecurityInterceptor securityInterceptor = new SecurityInterceptor(); registry.addInterceptor(securityInterceptor).addPathPatterns("/auth/**").addPathPatterns("/login"); }
程式碼改寫如下就可以了
@Bean public SecurityInterceptor securityInterceptor() { return new SecurityInterceptor(); } /** * 註冊 Interceptor */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(securityInterceptor()).addPathPatterns("/auth/**").addPathPatterns("/login"); }
你必須 登入 才能發表評論。