菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
389
0

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

原创
05/13 14:22
阅读数 46053

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.

发表评论

0/200
389 点赞
0 评论
收藏