zoukankan      html  css  js  c++  java
  • 在ContextLoaderListener中使用注解注入的类和job中使用注解注入的类

    场景:在ContextLoaderListener子类中加载job,为JobFactory的实现类声明@Component后,在ContextLoaderListener子类中为scheduler设置JobFactory。(主要解决的问题:在spring与quartz调用job时,job中无法读取注解类,实现注入)

    步骤一:

    ContextLoaderListener子类中contextInitialized方法中代码如下:

    super.contextInitialized(event);
    
    applicationContext = super.getCurrentWebApplicationContext();
    
            scheduler = applicationContext.getBean(Scheduler.class);
    
    try {
    
      scheduler.setJobFactory(applicationContext.getBean(JobFactory.class));
    
     } catch (BeansException e1) {
    
      logger.error(e1.getMessage(),e1);
    
     } catch (SchedulerException e1) {
    
      logger.error(e1.getMessage(),e1);
    
     }

    步骤二: 声明JobFactory子类,和job中的服务类

    package com.river.job.listener;
    
    import org.quartz.spi.TriggerFiredBundle;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
    import org.springframework.scheduling.quartz.AdaptableJobFactory;
    import org.springframework.stereotype.Component;
    
    @Component
    public class MyJobFactory extends AdaptableJobFactory {
        // 这个对象Spring会帮我们自动注入进来,也属于Spring技术范畴.
        @Autowired
        private AutowireCapableBeanFactory capableBeanFactory;
        protected Object createJobInstance(TriggerFiredBundle bundle)
                throws Exception {
            // 调用父类的方法
            Object jobInstance = super.createJobInstance(bundle);
            // 进行注入,这属于Spring的技术,不清楚的可以查看Spring的API.
            capableBeanFactory.autowireBean(jobInstance);
            return jobInstance;
        }
    }
    package com.river.service1;
    
    import org.springframework.stereotype.Service;
    
    @Service
    public class TestBean {
    
    }

    步骤三:在spring-job.xml中加入要注入的包扫描

    <context:component-scan base-package="com.river.job.listener" />
    <context:component-scan base-package="com.river.service1" />

    现在就可以测试一下,在job中测试结果如下:

    river_Worker-2===============com.river.job.HiJobImp@596b2557  2015-09-07 18:41:30
    com.river.service1.TestBean@7efd6242

    可见这里拿到TestBean的对象了。

  • 相关阅读:
    HashTable、HashSet和Dictionary的区别
    CCF_ 201312-3_最大的矩形
    CCF_ 201312-2_ISBN号码
    CCF_201312-1_出现次数最多的数
    CCF_ 201509-2_日期计算
    CCF_ 201512-3_画图
    CCF_ 201512-2_消除类游戏
    CCF_ 201409-2_画图
    CCF_201409-1_相邻数对
    CCF_ 201412-1_门禁系统
  • 原文地址:https://www.cnblogs.com/river2005/p/4789672.html
Copyright © 2011-2022 走看看