gpt4 book ai didi

java - 通过名称调用服务时,服务因空指针而失败,而在调用休息时则正常工作

转载 作者:行者123 更新时间:2023-12-01 19:51:18 25 4
gpt4 key购买 nike

我有一个可运行的类

public class MissingPartitionsTask implements Runnable {
@Autowired
private PartitionsService partitionsService;

private Schedules schedule;

MissingPartitionsTask(Schedules schedule){
this.schedule = schedule;
}

@Override
public void run() {
partitionsService.findAll(schedule.getId());
}
}

当我运行它时,我得到

java.lang.NullPointerException
at MissingPartitionsTask.run(MissingPartitionsTask.java:26)

这是第 26 行

partitionsService.findAll(schedule.getId());

我检查了schedule.getId() 。它不是空的。表中有 3 行,id 分别为 1、2 和 3。

我也有服务

@GetMapping("/partitions/{id}")
public List<LocalDate> findAll(@PathVariable long id) {
return partitionsService.findAll(id);
}

当我使用浏览器调用它并返回日期列表时,它就会起作用。

http://localhost:8181/partitions/3

为什么MissingPartitionsTask不工作?

编辑我的应用程序类

@SpringBootApplication
@EnableScheduling
@EnableAsync
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

编辑2

@Service
public class SchedulerService {
@Autowired
private ScheduleRepository scheduleRepository;

@Autowired
private TaskExecutor taskExecutor;

@Scheduled(fixedRate=60000)
public void scheduleAll() {
scheduleRepository.findAll().forEach(
schedule -> {
MissingPartitionsTask missingPartitionsTask = new MissingPartitionsTask(schedule);
taskExecutor.execute(missingPartitionsTask);
});
}

}

编辑3

Why is my Spring @Autowired field null?

没有帮助。我的服务是自动连接的

@Autowired
private PartitionsService partitionsService;

并带注释

@Service
public class PartitionsService {

时间表不为空。它返回值。

@Override
public void run() {
System.out.println(schedule.getId());
}

结果 1 2 3

当我执行 GET 操作时,该服务可以工作,但当我尝试从线程调用它时,该服务无法工作。

编辑4

This helped

问题是 Spring 无法控制我的可运行对象。将我的运行方法移至 SchedulerService 为

private Runnable newRunnable(Schedules schedule) {
return () -> {
List<String> missing = partitionsService.findMissing(schedule.getId());
};
}

并这样调用它

taskExecutor.execute(newRunnable(schedule));

而不是

taskExecutor.execute(missingPartitionsTask);

解决了。

最佳答案

您必须运行应用程序而不是单个类作为独立应用程序才能正常工作。当您使用 Autowiring 时,spring 必须初始化此类,然后您必须调用该函数。如果直接运行此类,将不会有可用的 Autowiring 类,并且您将得到空指针异常。

希望这有帮助

关于java - 通过名称调用服务时,服务因空指针而失败,而在调用休息时则正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59085821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com