Spring引导中的Quartz Job中的@Autowired组件

时间:2017-05-06 19:42:36

标签: java spring quartz-scheduler quartz

我遇到了Quartz和Spring实现的问题。 当我在Quartz Job中自动装配一个组件时,我收到了这个错误:

org.quartz.SchedulerException: Job instantiation failed
at org.springframework.scheduling.quartz.AdaptableJobFactory.newJob(AdaptableJobFactory.java:45) ~[spring-context-support-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.quartz.core.JobRunShell.initialize(JobRunShell.java:127) ~[quartz-2.2.3.jar:na]
at org.quartz.core.QuartzSchedulerThread.run(QuartzSchedulerThread.java:375) [quartz-2.2.3.jar:na]Caused by: java.lang.InstantiationException: com.kaloudia.api.quartz.jobs.ArticlePublicationJob
at java.lang.Class.newInstance(Class.java:427) ~[na:1.8.0_131]
at org.springframework.scheduling.quartz.AdaptableJobFactory.createJobInstance(AdaptableJobFactory.java:58) ~[spring-context-support-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.scheduling.quartz.AdaptableJobFactory.newJob(AdaptableJobFactory.java:41) ~[spring-context-support-4.3.3.RELEASE.jar:4.3.3.RELEASE]
... 2 common frames omittedCaused by: java.lang.NoSuchMethodException: com.kaloudia.api.quartz.jobs.ArticlePublicationJob.<init>()
at java.lang.Class.getConstructor0(Class.java:3082) ~[na:1.8.0_131]
at java.lang.Class.newInstance(Class.java:412) ~[na:1.8.0_131]
... 4 common frames omitted

我使用@Autowired注释来获取BlogManager的实例,但是当我的代码去掉时,我可以看到这个变量为null。 您有什么想法,我如何在Quartz Job类中获得BlogManager类?

我的工作班:

@Service
public class ArticlePublicationJob implements Job {

private Logger logger = LoggerFactory.getLogger(ArticlePublicationJob.class);
public static final String ARTICLE_ID = "ARTICLE_ID";

private final BlogManager blogManager;

@Autowired
public ArticlePublicationJob(BlogManager blogManager) {
    this.blogManager = blogManager;
}

public void execute(JobExecutionContext context)
        throws JobExecutionException {
    JobDataMap data = context.getJobDetail().getJobDataMap();
    Integer articleId = data.getInt(ARTICLE_ID);
    blogManager.actionOnArticle(articleId, "publish", 0);
}
}

和我的Quartz Manager:

public class QuartzManager {

private final SchedulerFactoryBean schedulerFactoryBean;

@Inject
public QuartzManager(SchedulerFactoryBean schedulerFactoryBean) {
    this.schedulerFactoryBean = schedulerFactoryBean;
}

public void schedulePublishArticleTrigger(Integer articleId, java.util.Calendar publishDate) throws SchedulerException {
    Scheduler sched = schedulerFactoryBean.getScheduler();
    JobDetail job = JobBuilder.newJob(ArticlePublicationJob.class)
            .withIdentity("article_" + articleId, "blog").build();
    job.getJobDataMap().put(ArticlePublicationJob.ARTICLE_ID, articleId);
    Trigger trigger = TriggerBuilder.newTrigger()
            .withIdentity("PublishArticle_" + articleId, "blog")
            .startAt(publishDate.getTime())
            .forJob("article_" + articleId, "blog")
            .build();
    sched.scheduleJob(job, trigger);
}
}

0 个答案:

没有答案