A Spring Boot Scheduled Problem

Solutions And Analysis

Posted by MichaelChen on 2020-11-26
Estimated Reading Time 1 Minutes
Words 331 In Total
Viewed Times

A Spring Boot Schedule Problem

Problem

@AutoWired cause a NullPointException

Source Code

Timer.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Configuration //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
public class SimpleScheduleConfig {

private ArrangeService arrangeService = new ArrangeService();
private SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd");

//3.添加定时任务
@Scheduled(cron = "0 0 0 * * ?") //秒 分 时 月的某一天 月 周几
private void configureTasks() {

Date date = DateRun.getFutureDate(7);
String d = dateFormat.format(date);
arrangeService.insertTwoWeekArrange(d);
System.err.println("执行定时任务1: " + LocalDateTime.now());
}
}

Service

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
public void insertTwoWeekArrange(String date_str){

Date date = new Date();
try {
date = sdf.parse(date_str);
} catch (ParseException e) {
System.err.println("日期格式错误:"+" "+ LocalDateTime.now());
e.printStackTrace();
}

List<PlanDto> planList = planMapper.selectDefaultPlan();

for (PlanDto planDto : planList) {
System.out.println(planDto.toString());
planDto.setTime(date);
arrangeMapper.insertArrangeByDate(planDto);
for (Doctor_Plan doctor_plan : planDto.getDoctor_plans()){
doctor_plan.setPlan_id(planDto.getId());
arrangeMapper.insertArrangeDoctorByDate(doctor_plan);
}
}
System.out.println(planList.toString());

}

Analysis

​ The @EnableScheduling has run before you use the object arrangeMapper .So the NullPointException happened.

Solution

​ use SpringContextHolder.getBean() to create arrangeMapper object instead of @AutoWired

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Configuration //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
public class SimpleScheduleConfig {

private ArrangeService arrangeService = new ArrangeService();
private SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd");

//3.添加定时任务
@Scheduled(cron = "0 0 0 * * ?") //秒 分 时 月的某一天 月 周几
private void configureTasks() {

PlanMapper planMapper = SpringContextHolder.getBean(PlanMapper.class);
ArrangeMapper arrangeMapper = SpringContextHolder.getBean(ArrangeMapper.class);
Date date = DateRun.getFutureDate(7);
String d = dateFormat.format(date);
arrangeService.insertTwoWeekArrange(d,planMapper,arrangeMapper);
System.err.println("执行定时任务1: " + LocalDateTime.now());
}
}

If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !