其他分享
首页 > 其他分享> > SpringBoot手动获取Bean

SpringBoot手动获取Bean

作者:互联网

SpringBoot手动获取Bean

此事起因是用多线程编写定时任务,任务结束后有存储数据库的操作。我在线程的实现类里自动注入dao类,结果执行save操作报注入类实例空指针异常。

Exception in thread "bd213f61a79f4436bf8f0bcd668a8e07" java.lang.NullPointerException: Cannot invoke "com.lhx.upgrade.repositories.UpgradeRecordRepository.save(Object)" because "this.recordRepository" is null

看来Spring是不会给线程自动注入。

找到一种手工从bean工厂获取依赖的办法:

@Component
public class BeanFactory implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext arg0) throws BeansException {
        // TODO Auto-generated method stub
        BeanFactory.applicationContext = arg0;
    }
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }
}

在线程的run函数里添加下面代码即可

UpgradeRecordRepository recordRepository = BeanFactory.getBean(UpgradeRecordRepository.class);
recordRepository.save(record);

标签:applicationContext,SpringBoot,ApplicationContext,手动,getBean,Bean,static,recordRe
来源: https://www.cnblogs.com/longhx/p/15741114.html