EasyExcel listener無法通過Autowired注入xxMapper

easyexcel listener無法通過Autowired注入xxMapper

文章目錄

  • easyexcel listener無法通過Autowired注入xxMapper
    • bug記錄:
    • 解決方案:
    • easyexcel 使用例子
      • controller
      • ServiceImpl
      • listener

bug記錄:

productMapper注入一直為null,而procureDetailMapper卻正常注入?

@Slf4j
@Component
public class ProductInfoExcelListener<T> extends AnalysisEventListener<T> {/*** 緩存的數據*/private List<ProductEntity> cachedDataList = ListUtils.newArrayList();/*** 存臨時表的數據*/
//    private List<ProcureDetailEntity> tempDataList = ListUtils.newArrayList();private final StringBuilder errMsg = new StringBuilder();private boolean hasException = false;private boolean hasNext = true;private IProcureDetailMapper procureDetailMapper;@Autowiredprivate IProductMapper productMapper;public ProductInfoExcelListener(IProcureDetailMapper procureDetailMapper) {this.procureDetailMapper = procureDetailMapper;}// 每解析一行數據就會調用一次該方法 todo@Overridepublic void invoke(T t, AnalysisContext analysisContext) {// 獲取行號int index = analysisContext.readRowHolder().getRowIndex() + 1;ProductExcelVo data = (ProductExcelVo) t;String productId = data.getProductId();String productNum = data.getProductNum();String categoryName = data.getCategoryName();String specName = data.getSpecName();if (!StringUtils.hasText(productId)) {hasException = true;setErrMsg(index, ":商品條碼不能為空");return;}if (!StringUtils.hasText(productNum)) {hasException = true;setErrMsg(index, ":商品數量不能為空");return;}if (StringUtils.hasText(productNum)) {int productNumInteger = Integer.parseInt(productNum);if (productNumInteger <= 0) {hasException = true;setErrMsg(index, ":商品數量不能小于0");return;}}if (!StringUtils.hasText(categoryName)) {hasException = true;setErrMsg(index, ":分類名稱不能為空");return;}//根據商品條碼查詢對應的分類信息ProductEntity productBaseDByProductId = productMapper.findProductBaseDByProductId(productId);if (productBaseDByProductId == null) {hasException = true;setErrMsg(index, ":該商品不存在");return;}if (!productBaseDByProductId.getCategoryName().equals(categoryName)) {hasException = true;setErrMsg(index, ":該商品的分類名稱有誤");return;}cachedDataList.add(productBaseDByProductId);log.info("invoke" + index);}@Overridepublic void doAfterAllAnalysed(AnalysisContext analysisContext) {// excel解析完畢以后需要執行的代碼
//        saveData()log.info("doAfterAllAnalysed ");}public List getCachedDataList() {return cachedDataList;}private void setErrMsg(int index, String msg) {this.hasNext = false;this.hasException = true;errMsg.append("第").append(index).append(msg);log.error("row {} org data verify failure:{};", index, msg);}public StringBuilder getErrMsg() {return errMsg;}public boolean isHasException() {return hasException;}
}
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class ProcureDetailServiceImpl implements IProcureDetailService {private final IProcureDetailMapper procureDetailMapper;@Overridepublic ProductInfo uploadAndParseExcel(MultipartFile file) throws IOException, CustomException {ProductInfoExcelListener<ProductExcelVo> listener = new ProductInfoExcelListener<>(procureDetailMapper);EasyExcel.read(file.getInputStream(),ProductExcelVo.class,listener).sheet().doRead();System.out.println("*******************");System.out.println(listener.getCachedDataList().size() == 0);System.out.println("1111111111111111111");List<ProductEntity> cachedDataList = listener.getCachedDataList();log.info("isHasException:{}", listener.getErrMsg());if(listener.isHasException()){throw new CustomException(CommonConstant.ErrorConstants.EXCEL_UNKNOWN_ERROR.getCode(), listener.getErrMsg().toString());}for (ProductEntity p: cachedDataList){System.out.println(p.toString());}return null;}
}

springboot在listener和filter中注入mapper會為null?

解決方案:

  1. https://codeleading.com/article/13375080759/
  2. 構造器注入

easyexcel 使用例子

<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.1.0</version></dependency>

controller

 @Slf4j
@RestController
@RequestMapping("/api-procure/procureController")
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class ProcureController extends BaseController {private final IProcureDetailService procureDetailService;/*** 上傳excel并且校驗解析 procure** @param file      excel* @param loginUser 登錄用戶* @return* @throws Exception*/@PostMapping("/uploadExcel/procure")public Result<ProductInfo> uploadExcelP(@RequestBody MultipartFile file, @LoginUser LoginUserBean loginUser) throws Exception {log.info("upload excel file:{}", file.getName());ProductInfo data = procureDetailService.uploadAndParseExcel(file, loginUser, CommonConstant.Type.PROCURE.getCode());return Result.succeed(data, "上傳成功");}
}

ServiceImpl

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class ProcureDetailServiceImpl implements IProcureDetailService {private final IProcureDetailMapper procureDetailMapper;@Overridepublic ProductInfo uploadAndParseExcel(MultipartFile file, LoginUserBean loginUser, String type) throws IOException, CustomException {ProductInfoExcelListener<ProductExcelVo> listener = new ProductInfoExcelListener<>(procureDetailMapper, productMapper);EasyExcel.read(file.getInputStream(),ProductExcelVo.class,listener).sheet().doRead();if (listener.getCachedDataList().size() == 0) {throw new CustomException(CommonConstant.ErrorConstants.EXCEL_UNKNOWN_ERROR.getCode(), "沒有有效數據");}List<ProcureDetailEntity> cachedDataList = listener.getCachedDataList();log.info("isHasException:{}", listener.getErrMsg());if (listener.isHasException()) {throw new CustomException(CommonConstant.ErrorConstants.EXCEL_UNKNOWN_ERROR.getCode(), listener.getErrMsg().toString());}
//        for (ProductEntity p : cachedDataList) {
//            System.out.println(p.toString());
//        }if (cachedDataList == null || cachedDataList.size() == 0) {throw new CustomException(CommonConstant.ErrorConstants.EXCEL_UNKNOWN_ERROR.getCode(), "未檢測到有效數據");}String userId = loginUser.getUserId();Date date = new Date();//申請標號采購申請單ID 訂單//“P”+YYYYMMDDHHMMSS+6位隨機數  “PO”+YYYYMMDDHHMMSS+6位隨機數String pattern = "YYYYMMDDHHMMSS";SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);String format = dateFormat.format(date);int i = (int) ((Math.random() * 9 + 1) * 100000);String procureId;if (type.equals(CommonConstant.Type.PROCURE.getCode())) {procureId = "P" + format + i;} else if (type.equals(CommonConstant.Type.ORDER.getCode())) {procureId = "PO" + format + i;} else {procureId = null;log.info("這一步執行到就完蛋了");}//存入t_procure_detail_tmp表procureDetailMapper.batchInsertProcureDetailTempList(procureId, userId, date, cachedDataList);//返回響應實體列表ProductInfo productInfo = new ProductInfo();List<ProcureDetailEntity> list = cachedDataList.stream().map(e -> {e.setProcureId(procureId);return e;}).collect(Collectors.toList());productInfo.setProductList(list);return productInfo;}
}

listener

/*** @description <采購申請解析返回的excel信息監聽器>* <p>* <p>* 解析模板導入的數據,對商品條碼、分類名稱、規格名稱校驗其有效性是否存在,對數量校驗大于0.其數據保存在采購單商品臨時表.* @author: zhouchaoyu* @Date: 2023-11-14*/
@Slf4j
@Component
public class ProductInfoExcelListener<T> extends AnalysisEventListener<T> {/*** 緩存的數據*/private List<ProcureDetailEntity> cachedDataList = ListUtils.newArrayList();/*** 存臨時表的數據*/
//    private List<ProcureDetailEntity> tempDataList = ListUtils.newArrayList();private final StringBuilder errMsg = new StringBuilder();private boolean hasException = false;private boolean hasNext = true;private IProcureDetailMapper procureDetailMapper;private IProductMapper productMapper;public ProductInfoExcelListener(IProcureDetailMapper procureDetailMapper, IProductMapper productMapper) {this.procureDetailMapper = procureDetailMapper;this.productMapper = productMapper;}// 每解析一行數據就會調用一次該方法 todo@Overridepublic void invoke(T t, AnalysisContext analysisContext) {// 獲取行號int index = analysisContext.readRowHolder().getRowIndex() + 1;ProductExcelVo data = (ProductExcelVo) t;String productId = data.getProductId();String productNum = data.getProductNum();String categoryName = data.getCategoryName();String specName = data.getSpecName();if (!StringUtils.hasText(productId)) {hasException = true;setErrMsg(index, ":商品條碼不能為空");return;}if (!StringUtils.hasText(productNum)) {hasException = true;setErrMsg(index, ":商品數量不能為空");return;}if (StringUtils.hasText(productNum)) {int productNumInteger = Integer.parseInt(productNum);if (productNumInteger <= 0) {hasException = true;setErrMsg(index, ":商品數量不能小于0");return;}}if (!StringUtils.hasText(categoryName)) {hasException = true;setErrMsg(index, ":分類名稱不能為空");return;}//根據商品條碼查詢對應的分類信息ProductEntity productBaseDByProductId = productMapper.findProductBaseDByProductId(productId);if (productBaseDByProductId == null) {hasException = true;setErrMsg(index, ":該商品不存在");return;}if (!productBaseDByProductId.getCategoryName().equals(categoryName)) {hasException = true;setErrMsg(index, ":該商品的分類名稱有誤");return;}String uid = IdGenerator.getIdStr() ;ProcureDetailEntity procureDetailEntity = new ProcureDetailEntity();procureDetailEntity.setId(uid);procureDetailEntity.setProductId(productBaseDByProductId.getProductId());procureDetailEntity.setProductNum(Integer.parseInt(productNum));procureDetailEntity.setCategoryId(productBaseDByProductId.getCategoryId());procureDetailEntity.setSpecId(specName);procureDetailEntity.setRowStatus("1");procureDetailEntity.setProductName(productBaseDByProductId.getProductName());procureDetailEntity.setCategoryName(productBaseDByProductId.getCategoryName());procureDetailEntity.setInventoryCount(productBaseDByProductId.getInventoryCount());BigDecimal costPrice = productBaseDByProductId.getCostPrice();BigDecimal totalPrice = costPrice.multiply(new BigDecimal(productNum)).setScale(2, RoundingMode.HALF_UP);procureDetailEntity.setTotalPrice(totalPrice);cachedDataList.add(procureDetailEntity);log.info("invoke" + index);}@Overridepublic void doAfterAllAnalysed(AnalysisContext analysisContext) {// excel解析完畢以后需要執行的代碼
//        saveData()log.info("doAfterAllAnalysed ");}public List<ProcureDetailEntity> getCachedDataList() {return cachedDataList;}private void setErrMsg(int index, String msg) {this.hasNext = false;this.hasException = true;errMsg.append("第").append(index).append(msg);log.error("row {} org data verify failure:{};", index, msg);}public StringBuilder getErrMsg() {return errMsg;}public boolean isHasException() {return hasException;}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/161186.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/161186.shtml
英文地址,請注明出處:http://en.pswp.cn/news/161186.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Visual Studio(VS) C++程序LNK2005錯誤,提示“error LNK2005: _XXX已經在xxx.obj中定義”解決方案

1.問題如圖 2.出現原因 項目中有多個源文件或頭文件&#xff0c;include后導致有些變量重復定義&#xff0c;加上Visual Studio新版版要求更嚴格 3.解決辦法 查詢到的解決辦法很多不好用&#xff0c;此處記錄解決自己問題的一個辦法&#xff1a;直接讓編譯器忽略第二次定義的…

圖形數據庫的實戰應用:如何在 Neo4j 中有效管理復雜關系

關系數據庫管理系統( RDBMS ) 代表了最先進的技術&#xff0c;這在一定程度上要歸功于其由周邊技術、工具和廣泛的專業技能組成的完善的生態系統。 在這個涵蓋信息技術(IT) 和運營技術(OT) 的技術革命時代&#xff0c;人們普遍認識到性能方面出現了重大挑戰&#xff0c;特別是…

連續變量降維:主成分分析和因子分析

主成分分析&#xff08;Principal Component Analysis&#xff0c;PCA&#xff09;和因子分析&#xff08;Factor Analysis&#xff09;都是用于處理連續變量降維的統計方法&#xff0c;它們在數據分析和特征提取中經常被使用。盡管它們有一些相似之處&#xff0c;但它們的目標…

初識JVM(簡單易懂),解開JVM神秘的面紗

目錄 一、什么是JVM&#xff08;Java虛擬機&#xff09;&#xff1f; 二、JVM的功能 三、JVM的功能-即時編譯 四、常見的JVM 五、JVM的組成 五、JVM的工作流程 參考資料 一、什么是JVM&#xff08;Java虛擬機&#xff09;&#xff1f; 在Java的世界里&#xff0c;Java虛…

代碼文檔瀏覽器 Dash mac中文版軟件特色

Dash mac是一個基于 Python 的 web 應用程序框架&#xff0c;它可以幫助開發者快速構建數據可視化應用。Dash 的工作原理是將 Python 代碼轉換成 HTML、CSS 和 JavaScript&#xff0c;從而在瀏覽器中呈現交互式的數據可視化界面。Dash 提供了一系列組件&#xff0c;包括圖表、表…

如何將設置為靜態IP的VMware虛擬機進行克隆以便可以復刻相應的環境

一定要關閉需要克隆的虛擬機右鍵要選擇克隆的虛擬機&#xff0c;選擇管理->克隆&#xff0c;進入克隆虛擬機向導 設定克隆出來的虛擬機名稱以及位置&#xff0c;選擇完成 克隆完成之后將會生成虛擬機&#xff0c;示例中生成的虛擬機為ubuntu-dev2 因為原本的虛擬機為靜態ip的…

區域人員超限AI算法的介紹及TSINGSEE視頻智能分析技術的行業應用

視頻AI智能分析已經滲透到人類生活及社會發展的各個方面。從生活中的人臉識別、停車場的車牌識別、工廠園區的翻越圍欄識別、入侵識別、工地的安全帽識別、車間流水線產品的品質缺陷AI檢測等&#xff0c;AI智能分析技術無處不在。在某些場景中&#xff0c;重點區域的人數統計與…

3:kotlin 邏輯控制(Control flow)

向其他語言一樣&#xff0c;kotlin也有循環和邏輯控制 條件判斷&#xff08;Conditional expressions&#xff09; kotlin使用if和when來進行條件判斷 如果糾結選擇if還是when&#xff0c;建議使用when&#xff0c;因為它更能提高程序的健壯性 if 普通寫法 fun main() {val…

Java集合拓展01

1、List&#xff0c;Set&#xff0c;Map三者的區別 List&#xff1a;一個有序&#xff08;元素存入集合的順序和取出的順序一致&#xff09;容器&#xff0c;元素可以重復&#xff0c;可以插入多個null元素&#xff0c;元素都有索引。常用的實現類有 ArrayList、LinkedList 和…

EMG肌肉信號處理合集 (一)

本文歸納了常見的肌肉信號預處理流程&#xff0c;方便EMG信號的后續分析。使用pyemgpipeline庫 來進行信號的處理。文中使用了 UC Irvine 數據庫的下肢數據。 目錄 1 使用wrappers 定義數據類&#xff0c;來進行后續的操作 2 肌電信號DC偏置去除 3 帶通濾波器處理 4 對肌電…

SpringCloud - 新版淘汰 Ribbon,在 OpenFeign 中整合 LoadBalancer 負載均衡

目錄 一、LoadBalancer 負載均衡 1.1、前言 1.2、LoadBalancer 負載均衡底層實現原理 二、整合 OpenFeign LoadBalancer 2.1、所需依賴 2.2、具體實現 2.3、自定義負載均衡策略 一、LoadBalancer 負載均衡 1.1、前言 在 2020 年以前的 SpringCloud 采用 Ribbon 作為負載…

OOM問題排查+Jvm優化

OOM問題排查&#xff1a; 1、top命令&#xff1a;查看cpu和內存的使用情況。 2、jstat命令&#xff1a;查看YGC和FGC情況&#xff0c;一般都是老年代不夠用。導致OOM 3、jmap命令&#xff1a; 查看哪個類的實例過多,以每個類占用多少了內存。4、jstack 查看線程與線程之間的阻…

Linux用戶名用戶組命令

添加用戶(為sam用戶添加一個主目錄/home/sam) useradd -d /home/sam -m sam新建一個用戶gem,該用戶的登錄shell是/bin/sh,它屬于group用戶組&#xff0c;同時又屬于adm和root用戶組&#xff0c;其中group用戶組是其主組 添加用戶賬號就是在/etc/passwd文件中為新用戶添加一條記…

80基于matlab的小波包熵與模糊C均值聚類的故障診斷,以凱斯西儲大學軸承數據為例進行分析

基于matlab的小波包熵與模糊C均值聚類的故障診斷&#xff0c;以凱斯西儲大學軸承數據為例進行分析。對數據進行小波包分解后重構&#xff0c;然后提取各頻帶能量分布&#xff0c;后計算小波包熵進行故障診斷。輸出特征可視化結果。數據可更換自己的&#xff0c;程序已調通&…

Git遠程庫操作(GitHub)

GitHub 網址&#xff1a;https://github.com/ 創建遠程倉庫 遠程倉庫操作 命令名稱作用git remote -v查看當前所有遠程地址別名git remote add 別名 遠程地址起別名git push 別名 分支推送本地分支上的內容到遠程倉庫git clone 遠程地址將遠程倉庫的內容克隆到本地git pull 別…

文件格式校驗

json格式校驗 非嚴格模式 json.loads(data, strictFalse) 如果strict為false&#xff08;默認值為True&#xff09;&#xff0c;則字符串中允許使用控制字符。此上下文中的控制字符是那些字符代碼在0–31范圍內的字符&#xff0c;包括“\t”&#xff08;制表符&#xff09;、“…

基于STM32的色彩識別與分類算法優化

基于STM32的色彩識別與分類算法優化是一項與圖像處理和機器學習相關的研究任務&#xff0c;旨在實現高效的色彩識別和分類算法在STM32微控制器上的運行。本文將介紹基于STM32的色彩識別與分類算法優化的原理和實現步驟&#xff0c;并提供相應的代碼示例。 1. 色彩識別與分類概…

[SIGGRAPH-23] 3D Gaussian Splatting for Real-Time Radiance Field Rendering

pdf | proj | code 本文提出一種新的3D數據表達形式3D Gaussians。每個Gaussian由以下參數組成&#xff1a;中心點位置、協方差矩陣、可見性、顏色。通過世界坐標系到相機坐標系&#xff0c;再到圖像坐標系的仿射關系&#xff0c;可將3D Gaussian映射到相機坐標系&#xff0c;通…

.NET面試題2

1.請解釋一下C#中的委托&#xff08;Delegate&#xff09;。 委托是一種類型安全的函數指針&#xff0c;它可以將方法作為參數傳遞或存儲在變量中。通過委托&#xff0c;可以實現方法的回調、事件處理等功能。委托在C#中使用delegate關鍵字進行聲明&#xff0c;可以根據方法簽名…

c語言:用迭代法解決遞歸問題

題目&#xff1a; 解釋&#xff1a;題目的意思就是用迭代法的空間和時間復雜的太高了&#xff0c;需要我們減小空間與時間的復雜度&#xff0c;我就想到了迭代法&#xff0c;思路和代碼如下&#xff1a; #include <stdio.h> //這里是遞歸法轉迭代法 int main() {int x,i…