spring集成quartz,在集成Job类中注入spring bean

解决方法有两种:

第一种方式:不去继承QuartzJobBean或Job,只是一个独立的job bean,通过配置MethodInvokingJobDetailFactoryBean来实现;

<bean id="Demo" class="com.s.job.Demo"/>
    <bean id="Demo_JobDetailBean" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="name" value="job_name_myjob"/>
        <property name="targetObject" ref="Demo"/>
        <property name="targetMethod" value="run"/>
        <!--false表示串行,第一个结束,才开始第二个-->
        <property name="concurrent" value="false"/>
</bean>

第二种方式:继承QuartzJobBean或Job,但是要重写SchedulerFactoryBean的jobFactory。

<bean id="Demo_Job_JobDetailBean" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
        <property name="jobClass" value="com.s.job.Demo_Job"/>
        <property name="name" value="Job"/>
        <property name="group" value="group"/>
</bean>

重写 

import org.quartz.spi.TriggerFiredBundle;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;  
import org.springframework.scheduling.quartz.SpringBeanJobFactory;  
import org.springframework.stereotype.Component;  
  
/**
* 继承 SpringBeanJobFactory 或 AdaptableJobFactory
*/
@Component("QuartzJobFactory")  
public class MyQuartzJobFactory extends SpringBeanJobFactory {  
  
    @Autowired  
    private AutowireCapableBeanFactory beanFactory;  
  
    /** 
     *  
     * 这里覆盖了super的createJobInstance方法,对其创建出来的类再进行autowire。 
     *  
     */  
    @Override  
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {  
  
        Object jobInstance = super.createJobInstance(bundle);  
  
        beanFactory.autowireBean(jobInstance);  
  
        return jobInstance;  
  
    }  
}

最后配置

 
<!-- trigger -->  
    <bean id="Trigger"  
        class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">  
        <property name="jobDetail" ref="Demo_Job_JobDetailBean"></property>  
        <property name="cronExpression" value="0/5 * * * * ?"></property>  
    </bean>
<!-- schedule factory -->  
    <bean id="SpringJobSchedulerFactoryBean"  
        class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
        <property name="triggers">  
            <list>  
                <ref bean="Trigger" />  
            </list>  
        </property>  
        <property name="jobFactory" ref="QuartzJobFactory"></property>  
   </bean>

参考网址:

http://www.cnblogs.com/daxin/p/3608320.html

http://blog.csdn.net/leocnx/article/details/54573275

转载于:https://my.oschina.net/hellokuang/blog/1490302

评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符 “速评一下”
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页