gpt4 book ai didi

java - Spring无法在实现Quartz Job的类中注入(inject)Bean

转载 作者:行者123 更新时间:2023-12-02 11:21:49 26 4
gpt4 key购买 nike

我正在尝试从实现 Quartz Job 的类发送电子邮件,为此我必须 @Autowire 类内的 IEmailService。

这是我用来创建 Quartz 作业的方法:

@Override
public Boolean sendInfoEmail(ManifestationProp manifProp, ServletRequest request) throws SchedulerException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String token = httpRequest.getHeader("jwt_token");
if(token == null) {
System.out.println("(ManifestationPropDaoImp) - TOKEN NULL");
return false;
}
String email = tokenUtils.getUsernameFromToken(token);
User user = userDao.findUserByEmail(email);
if(update(manifProp) != null) {
Scheduler sc = StdSchedulerFactory.getDefaultScheduler();
sc.start();
JobKey jobKey = new JobKey("Job_"+manifProp.getId(),"group1");
if(!sc.checkExists(jobKey)) { System.out.println("-----------------------------------------------");
System.out.println("Scheduling a Job for Manifestation Prop with ID - "+ manifProp.getId());
System.out.println("Current time - " + new Date());
System.out.println("Scheduled time - NOW" );
System.out.println("User - "+ user.getEmail());
System.out.println("Manifestation Prop - "+manifProp.getName());
JobDataMap jdm = new JobDataMap();
jdm.put("manifProp",manifProp);
jdm.put("user", user);
JobDetail jobDetail = JobBuilder.newJob(QuartzInformUser.class)
.withIdentity(jobKey)
.usingJobData(jdm)
.build();
Trigger t = TriggerBuilder.newTrigger().withIdentity("SimpleTrigger_"+manifProp.getId()).startNow().build();
sc.scheduleJob(jobDetail, t);
System.out.println("-----------------------------------------------");
}else {
System.out.println(" *** Job_"+manifProp.getId()+" already exists! *** ");
}
return true;
}else {
System.out.println("Could not update manifestation prop!");
}
return false;
}

下面是实现Job接口(interface)的类的代码:

@Service
public class QuartzInformUser implements Job{

@Autowired
IEmailService emailService;

@Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
try {
JobDataMap dataMap = arg0.getJobDetail().getJobDataMap();
User user = (User)dataMap.get("user");
ManifestationProp manifProp = (ManifestationProp)dataMap.get("manifProp");
System.out.println("USER: "+user);
System.out.println("MANIFESTATION PROP: "+manifProp);
emailService.informUser(user,manifProp);
}catch(Exception e){
e.printStackTrace();
}
}
}

Quartz Job 创建得非常好,问题出在 QuartzInformUser 类中。 Spring 不会将 IEmailService 注入(inject)到类中,因此字段 emailServicenull 并且我得到以下异常:

enter image description here

如果有人知道如何解决这个问题,我将非常感谢您的帮助!预先感谢您!

最佳答案

您将需要使用各种 Quartz 组件的 spring 助手/实现,以便您创建的作业将由 spring 管理。

...是两个很好的起点(尽管您需要确保您查看的文档适合您正在使用的 spring 版本;例如 spring-boot 有一个用于调度/quartz 的启动器)

关于java - Spring无法在实现Quartz Job的类中注入(inject)Bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49858687/

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