Spring @Autowire with Quartz

时间:2015-08-27 09:31:39

标签: java spring annotations

在我的网络应用程序中,我有一个这样的类,其中dao自动装配并且工作正常

@RestController
@RequestMapping(value = "/devicecontrolpanel")
public class DeviceCtrlPanelController {


@Autowired
private DeviceDao dao;

然后在同一个包中我有这个类

@WebListener
public class QuartzListener extends QuartzInitializerListener {

@Autowired
private DeviceDao dao;

为什么dant dao在这里获得Autowired?工作本身就要开始了。我想把那个dao传递给我的工作

@Override
public void contextInitialized(ServletContextEvent sce) {
    System.out.println("autowired works?");
    if(dao==null)
        System.out.println("dao is null");
    super.contextInitialized(sce);
    ServletContext ctx = sce.getServletContext();
    StdSchedulerFactory factory = (StdSchedulerFactory) ctx.getAttribute(QUARTZ_FACTORY_KEY);
    try {
        Scheduler scheduler = factory.getScheduler();
        scheduler.getContext().put("aService", dao);
        JobDetail jobDetail = JobBuilder.newJob(RegisterLog.class).build();
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity("simple").withSchedule(
                CronScheduleBuilder.cronSchedule("0 0/1 * 1/1 * ? *")).startNow().build();
        scheduler.scheduleJob(jobDetail, trigger);
        scheduler.start();
    } catch (Exception e) {
        ctx.log("There was an error scheduling the job.", e);
    }
}

1 个答案:

答案 0 :(得分:0)

@Autowiring发生在两个在春天配置为bean的类之间。

QuartzListener is not configured as a bean,因此内部没有自动装配。

根据将其配置为bean的目的,将下面的任何一个注释放在QuartzListener上:

1) @Component,
2) @Service,
3) @Controller
4) @Repository 

在spring-config.xml中启用@Component扫描: -

<context:component-scan base-package="your_package" />