Java線程調用DAO、Servic報出空指針異常


項目中用到了多線程,但是線程異步操作時無法調用Service層和Dao層的函數,進行數據庫的讀取,然后就想辦法如何往異步線程中注入Service和Dao層的bean。

一直調試測試了很多

1. 編寫一個工具類作為從Spring中獲取bean,注意 如果是通過@注解實現的一定要加Configuration這個注解,否則抱出context的空指針異常錯誤。

package com.arm.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

/**
* @Author hett
* @Date 2021/4/27 9:07
**/
@Configuration
public class AllBeanService implements ApplicationContextAware {

private static ApplicationContext context;

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
AllBeanService.context = applicationContext;
}

public static Object getBean(String className){
if (context==null)
return null;
else
return context.getBean(className);
}
public static <T> T getBean(Class<T> type) {
return context.getBean(type);
}
public static ApplicationContext getApplicationContext(){
return context;
}
}


2. 在線程中使用工具類
dataAnalyService= (DataAnalyService) AllBeanService.getBean("dataAnalyService");

注意:("dataAnalyService") 這個名字與定義@service保持一致
/**
* @Author hett
* @Date 2021/4/26 15:14
**/
@Service(value = "dataAnalyService")
public class DataAnalyService {



經過多次調試終於完成了,特此分享這個bug
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM