Yanis26
Yanis26

Reputation: 247

Spring TaskScheduler Bean not injected

I need to schedule a job when the a session is created. So I created my HttpSessionListener :

@Component
public class WebSessionListener implements HttpSessionListener {

//@Autowired
@Qualifier(value = "taskScheduler")
private ThreadPoolTaskScheduler taskScheduler;
@Autowired
private PanierService panierService;

//Notification that a session was created.
@Override
public void sessionCreated(HttpSessionEvent httpSessionCreatedEvent) {

    Runnable viderPanier20mnJob = PanierJobs.getViderPanier20mnJob(httpSessionCreatedEvent.getSession());
    taskScheduler.schedule(viderPanier20mnJob, PanierJobs.getNextDateTime());
    System.out.println("Session Created Called! -----------------------");
}

But my big problem here is that my TaskScheduler bean is not injected (NoSuchBeanDefinition or sometimes it just pops a NullPointerException).

Here is my TaskScheduler (taken from an example where it was working) :

@Configuration
@EnableScheduling
@EnableAsync
public class JobSchedulingConfig{

  @Bean
   public ThreadPoolTaskExecutor taskExecutor() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        return executor;
    }

    @Bean
    public ThreadPoolTaskScheduler taskScheduler() {

        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        return scheduler;
    }
}

I'm using Spring Boot, I don't have a configuration file. It is Java based configuration (as seen on the second code snippet). @Autowired and @Qualifier don't work for TaskScheduler (works for PanierService)

Upvotes: 6

Views: 11192

Answers (1)

allenru
allenru

Reputation: 717

I ran into this with a simple Spring MVC web server. I was unable to find either a taskScheduler bean or the ScheduledTaskRegistrar bean in the context.

To solve this, I changed my configuration class to implement SchedulingConfigurer, and within the configureTasks method, I set the task scheduler to one which is explicitly declared in the configuration (as a bean.) Here's my java config:

@Configuration
@EnableScheduling
@EnableAsync
public class BeansConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setTaskScheduler(taskScheduler());
    }

    @Bean
    public TaskScheduler taskScheduler() {
        return new ConcurrentTaskScheduler(); //single threaded by default
    }
}

This has the unfortunate side effect of me declaring the task scheduler, instead of letting Spring default it as it sees fit. I chose to use the same (single threaded executor within a concurrent task scheduler) implementation as Spring 4.2.4 is using.

By implementing the SchedulingConfigurer interface, I've ensured that the task scheduler I created is the same one that Spring's scheduling code uses.

Upvotes: 9

Related Questions