【问题标题】:SpringBootApp NullPointerException with @Autowired repositorySpringBootApp NullPointerException 与 @Autowired 存储库
【发布时间】:2021-08-24 10:27:01
【问题描述】:

这是我的 Spring Boot 应用程序。 当我运行 main 方法时,总是抛出一个空指针异常。 我不知道为什么 @Autowired JsonReaderService 为空。正如我将其定义为组件。

它是项目 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;
}

}

这里我有一个类,它使用存储库@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 方法中不起作用。是因为它是静态的吗?

    @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 在 com.creditsuisse.demo.DemoApplication.main(DemoApplication.java:33) ... 5 更多`

【问题讨论】:

    标签: java spring-boot components autowired


    【解决方案1】:

    您需要运行SpringApplication.run(),因为此方法会启动整个 Spring 框架。由于您的代码中没有它,因此 bean 没有自动装配,并且 JsonReaderService 为空。您可以在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);
        }
    }
    

    【讨论】:

    • 感谢您的评论。我添加了行 SpringApplication.run(DemoApplication.class, args);但仍然是相同的异常:线程“restartedMain”org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)中的异常原因:java.lang.NullPointerException
    • 您可以将完整的堆栈跟踪添加到问题中吗?
    • 是的,在自动装配的 JsonReaderService 中抛出异常
    • @edibIsic,我已经用 CommandLineRunner 更新了答案,但没有使用静态。
    • 谢谢伙计。你摇滚!!!现在工作得很好。是因为命令行扫描仪吗?正确的。没有就不会这样做。所以再次感谢。祝您愉快。 :D
    猜你喜欢
    • 2019-07-22
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    • 2017-04-23
    • 2022-10-13
    • 1970-01-01
    相关资源
    最近更新 更多