问题遇到的现象和发生背景
问题:在springboot 注入静态变量出现为Null
背景:quartz框架定时任务的案例,
代码
1.TriggerClass.java
@Component
public class TriggerClass implements InitializingBean {
public void testTrigger() throws Exception{
System.out.println("开始初始化调度器");
//创建schedule实例
StdSchedulerFactory stdSchedulerFactory = new StdSchedulerFactory();
//获取调度器实例
Scheduler scheduler = stdSchedulerFactory.getScheduler();
System.out.println("开始初始化任务实例");
//创建一个JobDetail,把实现了Job接口的类绑定到JobDetail
JobDetail jobDetail = JobBuilder
.newJob(XiaoTengJob.class)
.withIdentity("测试")
.usingJobData("name", "yueteng")
.build();
System.out.println("开始初始化触发器");
CronTrigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("trigger")
.withSchedule(CronScheduleBuilder.cronSchedule("* * * * * ? *"))
.startNow()
.build();
//把SimpleTrigger和JobDetail注册给调度器
scheduler.scheduleJob(jobDetail,trigger);
System.out.println("开启调度器");
//开启调度器
scheduler.start();
}
@Override
public void afterPropertiesSet() throws Exception {
testTrigger();
}
}
2.XiaoTengJob.java
@Component
public class XiaoTengJob implements Job {
private static StartService startService;
@Autowired
private StartService startService1;
@PostConstruct
public void init() {
startService = startService1;
}
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
startService.execute();
System.out.println("当前时间" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
}
@Service
public class StartService {
public void execute(){
System.out.println("Service执行了");
}
}
运行结果及报错内容
在启动springboot时,前几次会报错,之后就正常了
我的解答思路和尝试过的方法
解答思路:quartz这个框架的job任务类是由java反射得到的 , 他是不交由spring管理的
尝试过的办法
在XiaoTengJob.java中使用:
@Autowired
public void setStartService(StartService startServiceArg){
startService = startServiceArg;
}
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
startService.execute();
System.out.println("当前时间" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
结果依旧还是先报几次错误,然后就正常了。
我想要达到的结果
之前的代码是每秒都要执行一次,如果换一下时间也会正常。
我想要的是,不报错正常运行,恳请热心网友解答。