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);