2

In my web app I have a class like this, in which dao gets autowired and works fine

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


@Autowired
private DeviceDao dao;

then in the same package I have this class

@WebListener
public class QuartzListener extends QuartzInitializerListener {

@Autowired
private DeviceDao dao;

Why isnt dao getting Autowired here? The job itself is starting. I want to pass that dao to my job

@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);
    }
}
coou
  • 33
  • 6
  • I think a @WebListener is not a spring managed bean, so autowiering does not work here. – Jens Aug 27 '15 at 09:34
  • I had trouble using WebListener and Component annotations on the same bean. I got past it by using Spring's Scheduled annotation instead of WebListener to schedule my task. – Vik David Nov 04 '15 at 20:24

2 Answers2

1

@WebListener is annotation from javax.servlet package so it won't @Autowire any component.

Anotate QuartzListener with @Component to tell Spring is a bean.

@WebListener
@Component
public class QuartzListener extends QuartzInitializerListener {

    @Autowired
    private DeviceDao dao;

}

UPDATE

I already tried adding @Component annotation. Nothing changes. If adding the @Component annotation does not work try:

  1. Try other Spring annotations @Service, @Controller or @Repository.

  2. manually autowiring.

  3. Get a DeviceCtrlPanelController instance in QuartzListener and use the autowired DeviceDao.

Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
0

@Autowiring happens between two classes which are configured as beans in spring.

QuartzListener is not configured as a bean, so no autowiring is happening inside it.

Put either of the annotations below on QuartzListener, based on its purpose to configure it as a bean:

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

Enable @Component scanning in spring-config.xml by:-

<context:component-scan base-package="your_package" />
Amit Bhati
  • 5,569
  • 1
  • 24
  • 45