簡體   English   中英

SpringBootApp NullPointerException 與 @Autowired 存儲庫

[英]SpringBootApp NullPointerException with @Autowired repository

這是我的 Spring 啟動應用程序。 當我運行 main 方法時,總是會拋出 null 指針異常。 我不知道為什么@Autowired JsonReaderService 是 null。 正如我將其定義為組件。

它是項目 src 文件夾中的子文件夾,因此 Main Method 位於源文件夾上方。 所以 spring 應該正確掃描它?

我也有一個工作得很好的測試方法。

 @SpringBootApplication
 public class DemoApplication {

@Autowired
private JsonReaderService jsonReaderService;

private static JsonReaderService stat_jsonReaderService;

static Logger logger = LoggerFactory.getLogger(DemoApplication.class);

public static void main(String[] args) throws IOException {

    String textFileName = scanFileName();
    Reader reader = Files.newBufferedReader(Paths.get("src/main/resources/" + textFileName));
    // This line is always null pointer exception. The @autowired Annotation don't work with my JsonReaderService????? WHY
    List<EventDataJson> jsonReaderServicesList = stat_jsonReaderService.readEventDataFromJson(reader);
    stat_jsonReaderService.mappingToDatabase(jsonReaderServicesList);

}

public static String scanFileName() {
    logger.info("Scanning keyboard input");
    System.out.println("enter a file to scan");
    Scanner scanInput = new Scanner(System.in);
    String text = scanInput.nextLine();
    logger.info("successful keyboard input was : " + text);
    return text;
}

@PostConstruct
public void init() {
    logger.info("initializing Demo Application");
    stat_jsonReaderService = jsonReaderService;
}

}

在這里,我有 class 它使用存儲庫 @Autowired 來保存一些實體,但我總是在 repository.save(...)

@Component
public class JsonReaderService {
static Logger logger = LoggerFactory.getLogger(DemoApplication.class);
@Autowired
EventDataRepository repository;
private Reader reader;
private List<EventDataJson> eventDataList;

@Autowired
public JsonReaderService(){}

public List<EventDataJson> readEventDataFromJson(Reader reader) throws IOException {

    try {
        logger.info("parsing event data from json started");
        Gson gson = new Gson();
        EventDataJson[] eventData = gson.fromJson(reader, EventDataJson[].class);
        eventDataList = Arrays.asList(eventData);
        reader.close();
    } catch (IOException e) {
        logger.error("Error while reading the json file");
        e.printStackTrace();
    }
    logger.info("parsing json eventData successful finished");
    return eventDataList;
}

public Boolean mappingToDatabase(List<EventDataJson> eventDataList) {
    logger.info("mapping from json to database eventData started ...");

    Set<String> idList = eventDataList.stream().map(EventDataJson::getId).collect(Collectors.toSet());
    for (String id : idList
    ) {
        Stream<EventDataJson> filteredEventDataList1 = eventDataList.stream().filter((item) -> item.getId().equals(id));
        Stream<EventDataJson> filteredEventDataList0 = eventDataList.stream().filter((item) -> item.getId().equals(id));
        EventDataJson startedEvent = filteredEventDataList1.filter((item) -> item.getState().equals("STARTED")).findAny().orElse(null);
        EventDataJson finishedEvent = filteredEventDataList0.filter((item) -> item.getState().equals("FINISHED")).findAny().orElse(null);
        long duration0 = finishedEvent.getTimestamp() - startedEvent.getTimestamp();
        Boolean alert;
        if (duration0 > 4) {
            alert = true;
        } else {
            alert = false;
        }
        try {
            this.repository.save(new EventDataDb(id, duration0, startedEvent.getType(), startedEvent.getHost(), alert));
            logger.info("mapping to Database Repository action successful");

        } catch (Exception e) {
            logger.error("Exception in database mapping occurred");
            e.printStackTrace();
            return false;

        }
    }
    return true;

}
}

帶注釋的存儲庫

@Repository
 public interface EventDataRepository extends JpaRepository<EventDataDb, String> {
 EventDataDb findAllById(String id);
 }

測試用例與 @autowired Annotation 一起工作得很好我不知道為什么它在 main 方法中不起作用。 是不是因為是static?

    @Autowired
       private EventDataRepository repository;

    @Autowired
       private JsonReaderService jReader;
    @Test
    public void whenParseJson_thenTransform_and_save_to_db() throws IOException {
    BufferedReader reader = Files.newBufferedReader(Paths.get("src/main/resources/" + "logfile.txt"));
    List<EventDataJson> eventDataList1 = jReader.readEventDataFromJson(reader);
    if (jReader.mappingToDatabase(eventDataList1)) {
        EventDataDb eventDataFromDb = this.repository.findAllById("scsmbstgra");
        Assertions.assertTrue(eventDataFromDb.getType().equals("APPLICATION_LOG"));
        Assertions.assertTrue(eventDataFromDb.getHost().equals("12345"));
        Assertions.assertTrue(eventDataFromDb.getAlert().equals(true));
        Assertions.assertTrue(eventDataFromDb.getDuration() == 5);
        logger.info("Assert successfully accomplished");
    } else
        logger.error("Could not persist eventData to DB Error");
}

堆棧跟蹤

`線程“restartedMain”中的異常 java.lang.reflect.InvocationTargetException

at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)

引起:java.lang.NullPointerException at com.creditsuisse.demo.DemoApplication.main(DemoApplication.Z93F725A07423FE1C889F448B33D21F465Z 更多:

您需要運行SpringApplication.run()因為此方法啟動整個 Spring 框架。 由於您的代碼中沒有它,因此 bean 沒有自動裝配,JsonReaderService 是 null。 您可以在Application.java中執行以下操作。 此外,由於這涉及從 CLI 獲取輸入,為什么不使用 CommandLineRunner,如下所示:

@SpringBootApplication
public class DemoApplication 
  implements CommandLineRunner {

    @Autowired
    private JsonReaderService jsonReaderService;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
 
    @Override
    public void run(String... args) {
        String textFileName = scanFileName();
        Reader reader = Files.newBufferedReader(Paths.get("src/main/resources/" + textFileName));
        List<EventDataJson> jsonReaderServicesList = stat_jsonReaderService.readEventDataFromJson(reader);
        jsonReaderService.mappingToDatabase(jsonReaderServicesList);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM