Spring TaskScheduler Bean未注入

Yan*_*s26 2 java jobs spring schedule task

创建会话时,我需要安排工作。所以我创建了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! -----------------------");
}
Run Code Online (Sandbox Code Playgroud)

但是我这里最大的问题是我的TaskScheduler bean没有被注入(NoSuchBeanDefinition或有时只是弹出NullPointerException)。

这是我的TaskScheduler(摘自工作所在的示例):

@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用Spring Boot,但没有配置文件。这是基于Java的配置(如第二个代码片段所示)。@Autowired和@Qualifier不适用于TaskScheduler(适用于PanierService)

all*_*nru 5

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
    }
}
Run Code Online (Sandbox Code Playgroud)

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.