从普通类调用JpaRepository时如何修复java.lang.NullPointerException?

时间:2019-04-12 03:41:27

标签: java spring-boot jpa

我是一名新的Java开发人员。我从普通类(不是main,不在控制器中,..)调用JpaRepository并得到错误:

java.lang.NullPointerException
    at com.wecommit.criticalService.controller.TableSpaceWarningCRC.doTransData(TableSpaceWarningCRC.java:34)

这是我的代码: 普通班:

    package com.wecommit.criticalService.critical;

import org.springframework.beans.factory.annotation.Autowired;

import com.wecommit.criticalService.entity.HistoryUpload;

public class CreateDataPerTable {

    HistoryUpload historyUpload;
    int l_historyUpload;

    @Autowired
    TableSpaceWarningCRC tableSpaceWarning;
    //Constructor
    public CreateDataPerTable(TableSpaceWarningCRC tableSpaceWarning) {
    }

    public void setHistoryUpload(HistoryUpload historyUpload) {
        //Get time_upload in historyUpload by historyUploadID

        this.historyUpload = historyUpload;
        l_historyUpload = historyUpload.getId();
    }   

    public void creatDataTables() {
//the error row bellow
            tableSpaceWarning.setTableSpaceWarningCRC(historyUpload);
            tableSpaceWarning.doTransData();


    }

}

然后类调用JpaRepository方法:

package com.wecommit.criticalService.critical;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.wecommit.criticalService.entity.TableSpace;
import com.wecommit.criticalService.repository.TableSpaceRepository;
import com.wecommit.criticalService.entity.HistoryUpload;

@Component
public class TableSpaceWarningCRC {
    HistoryUpload historyUpload;

    @Autowired
    TableSpaceRepository tableSpaceRepository;

        public TableSpaceWarningCRC() {
    }

    public void setTableSpaceWarningCRC(HistoryUpload historyUpload) {
        this.historyUpload = historyUpload;
    }
    public void doTransData() {
        //TableSpace Data
        List<TableSpace> listTableSpace;
        listTableSpace = tableSpaceRepository.findByLogFileId(historyUpload.getLogFileId());
            for (int i = 0; i < listTableSpace.size(); i++) {
                TableSpaceWarningCreateTableData tableSpaceWarningCreateTableData = new TableSpaceWarningCreateTableData(listTableSpace.get(i),historyUpload.getLogFileId());
            }
    }
}

我添加了许多符号,但是它不起作用。请帮我。 谢谢您阅读

1 个答案:

答案 0 :(得分:0)

您的类TableSpaceWarningCRC似乎不是spring bean。自动接线仅在Spring托管类中起作用。

尝试在TableSpaceWarningCRC类的顶部添加@Component批注,然后从应用程序上下文实例化该类,而不是调用构造函数。

How to get bean using application context in spring boot

此外,默认情况下,spring bean是单例。因此,如果您的类是有状态的或需要多个实例,请在bean定义中使用原型作用域

https://www.baeldung.com/spring-inject-prototype-bean-into-singleton