栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot中listener和interceptor中无法注入services和dao等其它bean

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot中listener和interceptor中无法注入services和dao等其它bean

问题描述:

在我们的监听器和拦截器类中使用@Resource自动注入dao时一直为空

@WebListener
@Component
public class BootServiceListener implements ServletContextListener {

    @Resource
    private SyncUploadRecordDao syncUploadRecordDao;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
		   System.out.println(syncUploadRecordDao);
    }
}

即使我加了@Component也和之前一样 dao为空

原因分析:

网上查询有的说是拦截器和监听器是在spring上下文之前加载的,那个时候其它的bean还没有生成,就会报空指针异常。

还没搞明白:这是和springbean工厂的加载顺序有关还是springboot的自动装配组装有关系,那个@Component无法生效,我在其它的bean里面使用这个监听器和拦截器的注入时便可以生效,或者通过@Bean来注入这个bean到工厂中?这样不就和我没用它它就注入不了,注入dao为空吗?

解决方案:

以下两种方法可以解决问题

在我们配置我们的监听器和拦截器的时候
我们不能直接new一个监听器对象和拦截器对象
而是应该使用bean工厂里面的那个

    @Resource
    private BootServiceListener bootServiceListener;

    @Bean
    public ServletListenerRegistrationBean listenerRegist() {
        ServletListenerRegistrationBean srb = new ServletListenerRegistrationBean();
        srb.setListener(bootServiceListener);
        System.out.println("listener");
        return srb;
    }

或者我们写一个方法注入bean

    @Bean
    public BootServiceListener getBootServiceListener(){
        return new BootServiceListener();
    }

    @Bean
    public ServletListenerRegistrationBean listenerRegist() {
        ServletListenerRegistrationBean srb = new ServletListenerRegistrationBean();
        srb.setListener(getBootServiceListener());
        System.out.println("listener");
        return srb;
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/708347.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号