HandlerInterceptor裡@Autowired物件為空的解決方法
阿新 • • 發佈:2018-12-30
That's because Spring isn't managing your PagePopulationInterceptor instance. You are creating it yourself in the below (攔截器內使用@Autowired時出現了null,這是由於你的spring物件注入時機在你的攔截器之後了)
public @Override void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new PagePopulationInterceptor()); }
change that to
@Bean
public PagePopulationInterceptor pagePopulationInterceptor() {
return new PagePopulationInterceptor();
}
public @Override void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(pagePopulationInterceptor());
}
in this way, Spring will manage the lifecycle of the PagePopulationInterceptor instance since it's generated from a @Bean method. Spring will scan it for @Autowired targets and inject them.
This assumes that PagePopulationInterceptor is in a package to be @ComponentScaned.