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