Java Spring任务调度器-未定义[org.springframework.scheduling.TaskScheduler]类型的合格bean

Java Spring任务调度器-未定义[org.springframework.scheduling.TaskScheduler]类型的合格bean,java,spring,spring-mvc,ubuntu,cron,Java,Spring,Spring Mvc,Ubuntu,Cron,错误:未定义[org.springframework.scheduling.TaskScheduler]类型的合格bean 这是我的控制台日志: 10:32:35.742 [localhost-startStop-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Eagerly caching bean 'cronTrigger' to allow for resolving potential circular references 10:32:3

错误:未定义[org.springframework.scheduling.TaskScheduler]类型的合格bean

这是我的控制台日志:

10:32:35.742 [localhost-startStop-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Eagerly caching bean 'cronTrigger' to allow for resolving potential circular references
10:32:35.746 [localhost-startStop-1] DEBUG o.s.s.a.ScheduledAnnotationBeanPostProcessor - No @Scheduled annotations found on bean class: class org.springframework.scheduling.support.CronTrigger
10:32:35.747 [localhost-startStop-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Finished creating instance of bean 'cronTrigger'
10:32:35.747 [localhost-startStop-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'taskExecutor'
10:32:35.747 [localhost-startStop-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating instance of bean 'taskExecutor'
10:32:35.747 [localhost-startStop-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'webConfig'
10:32:35.749 [localhost-startStop-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Eagerly caching bean 'taskExecutor' to allow for resolving potential circular references
10:32:35.757 [localhost-startStop-1] DEBUG o.s.s.a.ScheduledAnnotationBeanPostProcessor - No @Scheduled annotations found on bean class: class java.util.concurrent.ScheduledThreadPoolExecutor
10:32:35.757 [localhost-startStop-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Finished creating instance of bean 'taskExecutor'
10:32:35.757 [localhost-startStop-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'getInternalResourceViewResolver'
10:32:35.757 [localhost-startStop-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating instance of bean 'getInternalResourceViewResolver'
10:32:35.757 [localhost-startStop-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'webConfig'
10:32:35.770 [localhost-startStop-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Eagerly caching bean 'getInternalResourceViewResolver' to allow for resolving potential circular references
10:32:35.781 [localhost-startStop-1] DEBUG o.s.s.a.ScheduledAnnotationBeanPostProcessor - No @Scheduled annotations found on bean class: class org.springframework.web.servlet.view.InternalResourceViewResolver
10:32:35.781 [localhost-startStop-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Finished creating instance of bean 'getInternalResourceViewResolver'
10:32:35.785 [localhost-startStop-1] DEBUG o.s.w.c.s.AnnotationConfigWebApplicationContext - Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor@31b09c11]
10:32:35.785 [localhost-startStop-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
10:32:35.788 [localhost-startStop-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'delegatingApplicationListener'
10:32:35.788 [localhost-startStop-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.annotation.internalScheduledAnnotationProcessor'
10:32:35.788 [localhost-startStop-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'mvcResourceUrlProvider'
10:32:35.788 [localhost-startStop-1] DEBUG o.s.w.s.resource.ResourceUrlProvider - Looking for resource handler mappings
10:32:35.789 [localhost-startStop-1] DEBUG o.s.w.s.resource.ResourceUrlProvider - No resource handling mappings found
10:32:35.789 [localhost-startStop-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'webConfig'
10:32:35.794 [localhost-startStop-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'cronTrigger'
10:32:35.808 [localhost-startStop-1] DEBUG o.s.s.a.ScheduledAnnotationBeanPostProcessor - Could not find default TaskScheduler bean

//Exception Starts from here.
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.scheduling.TaskScheduler] is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:371) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:331) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.finishRegistration(ScheduledAnnotationBeanPostProcessor.java:183) [spring-context-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.onApplicationEvent(ScheduledAnnotationBeanPostProcessor.java:162) [spring-context-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.onApplicationEvent(ScheduledAnnotationBeanPostProcessor.java:85) [spring-context-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:151) [spring-context-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:128) [spring-context-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:331) [spring-context-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:773) [spring-context-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:483) [spring-context-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4726) [catalina.jar:8.0.20.B]
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5162) [catalina.jar:8.0.20.B]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [catalina.jar:8.0.20.B]
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725) [catalina.jar:8.0.20.B]
     at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701) [catalina.jar:8.0.20.B]
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717) [catalina.jar:8.0.20.B]
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:581) [catalina.jar:8.0.20.B]
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1683) [catalina.jar:8.0.20.B]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_45]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_45]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_45]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_45]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_45]
10:32:35.809 [localhost-startStop-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'taskExecutor'
10:32:35.827 [localhost-startStop-1] DEBUG o.s.c.e.PropertySourcesPropertyResolver - Searching for key 'spring.liveBeansView.mbeanDomain' in [servletConfigInitParams]
10:32:35.827 [localhost-startStop-1] DEBUG o.s.c.e.PropertySourcesPropertyResolver - Searching for key 'spring.liveBeansView.mbeanDomain' in [servletContextInitParams]
10:32:35.827 [localhost-startStop-1] DEBUG o.s.c.e.PropertySourcesPropertyResolver - Searching for key 'spring.liveBeansView.mbeanDomain' in [jndiProperties]
10:32:35.827 [localhost-startStop-1] DEBUG o.springframework.jndi.JndiTemplate - Looking up JNDI object with name [java:comp/env/spring.liveBeansView.mbeanDomain]
10:32:35.830 [localhost-startStop-1] DEBUG o.s.jndi.JndiLocatorDelegate - Converted JNDI name [java:comp/env/spring.liveBeansView.mbeanDomain] not found - trying original name [spring.liveBeansView.mbeanDomain]. javax.naming.NameNotFoundException: Name [spring.liveBeansView.mbeanDomain] is not bound in this Context. Unable to find [spring.liveBeansView.mbeanDomain].
10:32:35.830 [localhost-startStop-1] DEBUG o.springframework.jndi.JndiTemplate - Looking up JNDI object with name [spring.liveBeansView.mbeanDomain]
下面是WebConfig.java:

@Configuration
@EnableScheduling
@EnableWebMvc
@ComponentScan(basePackages="com.project")
public class WebConfig implements SchedulingConfigurer 
{    
protected static final Logger slf4jLogger  = Logger.getLogger(WebConfig.class.getName());
private static final String cronExpression = "0 0 * * * ?";



/*@Bean
public MobileNotifSchedulerBean schedulerbean()
{
    return new MobileNotifSchedulerBean();
}*/

@Bean
public InternalResourceViewResolver getInternalResourceViewResolver()
{
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/jsp/");
    resolver.setSuffix(".jsp");
    resolver.setSuffix(".html");
    resolver.setSuffix(".htm");
    return resolver;
}

@Bean
CronTrigger cronTrigger() 
{
    //String timeZone = "Asia/Calcutta";

    String timeZone = null;
    HashSet<String> userTimeZonesfromDB = FetchUserTimeZones.fetchUserTimeZone();
    for (String s : userTimeZonesfromDB) 
    {
        timeZone = s;
        slf4jLogger.info(s);
    }
    return new CronTrigger(cronExpression, TimeZone.getTimeZone(timeZone));
}


@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) 
{

    taskRegistrar.addCronTask(new CronTask(new MobileNotifSchedulerBean(), cronTrigger()));
}

@Bean(destroyMethod="shutdown")
public Executor taskExecutor() 
{
    return Executors.newScheduledThreadPool(1);
}   
}
@EnableScheduling
public class MobileNotifSchedulerBean implements Runnable 
{
protected static final Logger slf4jLogger  = Logger.getLogger(MobileNotifSchedulerBean.class.getName());


public void sendQuestionNotif() 
{
    try 
    {
        HashSet<String> reg_ids = FetchRegistrationIDs.fetchItems();
        for (String s : reg_ids) 
        {
            String REGISTRATION_IDs = s;
            slf4jLogger.info(s);                
            MobileSNSPushNotification.sendNotification(REGISTRATION_IDs);
        }
    } 
    catch (IOException e) 
    {
        //e.printStackTrace();
        slf4jLogger.error(e);
        slf4jLogger.error(e.getMessage());
        slf4jLogger.error(e.getStackTrace());
    }
}


@Override
public void run() 
{
    sendQuestionNotif();
}
}
@配置
@使能调度
@EnableWebMvc
@组件扫描(basePackages=“com.project”)
公共类WebConfig实现SchedulingConfigurer
{    
受保护的静态最终记录器slf4jLogger=Logger.getLogger(WebConfig.class.getName());
私有静态最终字符串cronExpression=“0***?”;
/*@豆子
公共移动智能调度Bean调度Bean()
{
返回新的MobileNotifSchedulerBean();
}*/
@豆子
公共InternalResourceViewResolver getInternalResourceViewResolver()
{
InternalResourceViewResolver解析器=新的InternalResourceViewResolver();
resolver.setPrefix(“/WEB-INF/jsp/”);
resolver.setSuffix(“.jsp”);
resolver.setSuffix(“.html”);
解析器.setSuffix(“.htm”);
返回解析器;
}
@豆子
CronTrigger CronTrigger()
{
//字符串时区=“亚洲/加尔各答”;
字符串时区=空;
HashSet UserTimeZones FromDB=FetchUserTimeZones.fetchUserTimeZone();
for(字符串s:userTimeZonesfromDB)
{
时区=s;
slf4jLogger.info;
}
返回新的CronTrigger(cronExpression,TimeZone.getTimeZone(TimeZone));
}
@凌驾
公共无效配置任务(ScheduledTaskRegistrar任务注册器)
{
addCronTask(新的CronTask(新的MobileNotifSchedulerBean(),cronTrigger());
}
@Bean(destromethod=“shutdown”)
公共执行者任务执行者()
{
返回Executors.newScheduledThreadPool(1);
}   
}
这是我的MobileNotifSchedulerBean:

@Configuration
@EnableScheduling
@EnableWebMvc
@ComponentScan(basePackages="com.project")
public class WebConfig implements SchedulingConfigurer 
{    
protected static final Logger slf4jLogger  = Logger.getLogger(WebConfig.class.getName());
private static final String cronExpression = "0 0 * * * ?";



/*@Bean
public MobileNotifSchedulerBean schedulerbean()
{
    return new MobileNotifSchedulerBean();
}*/

@Bean
public InternalResourceViewResolver getInternalResourceViewResolver()
{
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/jsp/");
    resolver.setSuffix(".jsp");
    resolver.setSuffix(".html");
    resolver.setSuffix(".htm");
    return resolver;
}

@Bean
CronTrigger cronTrigger() 
{
    //String timeZone = "Asia/Calcutta";

    String timeZone = null;
    HashSet<String> userTimeZonesfromDB = FetchUserTimeZones.fetchUserTimeZone();
    for (String s : userTimeZonesfromDB) 
    {
        timeZone = s;
        slf4jLogger.info(s);
    }
    return new CronTrigger(cronExpression, TimeZone.getTimeZone(timeZone));
}


@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) 
{

    taskRegistrar.addCronTask(new CronTask(new MobileNotifSchedulerBean(), cronTrigger()));
}

@Bean(destroyMethod="shutdown")
public Executor taskExecutor() 
{
    return Executors.newScheduledThreadPool(1);
}   
}
@EnableScheduling
public class MobileNotifSchedulerBean implements Runnable 
{
protected static final Logger slf4jLogger  = Logger.getLogger(MobileNotifSchedulerBean.class.getName());


public void sendQuestionNotif() 
{
    try 
    {
        HashSet<String> reg_ids = FetchRegistrationIDs.fetchItems();
        for (String s : reg_ids) 
        {
            String REGISTRATION_IDs = s;
            slf4jLogger.info(s);                
            MobileSNSPushNotification.sendNotification(REGISTRATION_IDs);
        }
    } 
    catch (IOException e) 
    {
        //e.printStackTrace();
        slf4jLogger.error(e);
        slf4jLogger.error(e.getMessage());
        slf4jLogger.error(e.getStackTrace());
    }
}


@Override
public void run() 
{
    sendQuestionNotif();
}
}
@EnableScheduling
公共类MobileNotifSchedulerBean实现可运行
{
受保护的静态最终记录器slf4jLogger=Logger.getLogger(MobileNotifSchedulerBean.class.getName());
public void sendQuestionNotif()
{
尝试
{
HashSet reg_id=fetchRegistrationId.fetchItems();
用于(字符串s:reg_id)
{
字符串注册\u id=s;
slf4jLogger.info;
MobileSNSPushNotification.sendNotification(注册标识);
}
} 
捕获(IOE异常)
{
//e、 printStackTrace();
slf4jLogger.错误(e);
slf4jLogger.error(e.getMessage());
slf4jLogger.error(例如getStackTrace());
}
}
@凌驾
公开募捐
{
sendQuestionNotif();
}
}
我正在使用Java8和SpringMVC4。我想解决这个错误 “未定义[org.springframework.scheduling.TaskScheduler]类型的合格bean”
请帮帮我。TIA.

@可配置
注释您的
MobileNotifySchedulerBean
。我认为它会起作用。

此异常记录于org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.inishRegistration()

if (this.registrar.hasTasks() && this.registrar.getScheduler() == null) {
    Assert.state(this.beanFactory != null, "BeanFactory must be set to find scheduler by type");
    try {
        // Search for TaskScheduler bean...
        this.registrar.setTaskScheduler(this.beanFactory.getBean(TaskScheduler.class));
    }
    catch (NoSuchBeanDefinitionException ex) {
        logger.debug("Could not find default TaskScheduler bean", ex);
        // Search for ScheduledExecutorService bean next...
        try {
            this.registrar.setScheduler(this.beanFactory.getBean(ScheduledExecutorService.class));
        }
        catch (NoSuchBeanDefinitionException ex2) {
            logger.debug("Could not find default ScheduledExecutorService bean", ex);
            // Giving up -> falling back to default scheduler within the registrar...
        }
    }
}
此进程尝试为注册器设置任务计划程序。为此,它尝试通过BeanFactory.getBean方法查找已注册的调度程序bean:

  • 尝试查找已配置的TaskScheduler bean,如果未找到,则返回 至->
  • 查找ScheduledExecutorService bean,如果未找到,则返回到->
  • 在注册器中使用默认调度程序 (上面的代码注释中也指出了这一点://放弃->退回到注册器中的默认调度程序…
  • 如果在容器中找不到任何TaskScheduler或ScheduledExecutorService bean,则BeanFactory.getBean会引发异常

    ScheduledAnnotationBeanPostProcessor依次以调试级别记录这些异常:

    logger.debug("Could not find default TaskScheduler bean", ex);
    logger.debug("Could not find default ScheduledExecutorService bean", ex);
    
    所以,总之,这些异常只是在为任务调度器bean查找回退选项的过程中记录的,它们不会影响应用程序的执行

    可以提升此类的日志级别,以便不会像这样记录这些调试级别消息:

    <!-- Elevate the log level for 'org.springframework.scheduling' since in
         process of registering the scheduled task, Spring's
         ScheduledAnnotationBeanPostProcessor tries to find TaskScheduler and
         ScheduledExecutorService beans and then fallbacks to its internal
         scheduler but in the process logs exceptions when it cannot find those
         beans registered.
    -->
    <logger name="org.springframework.scheduling">
        <level value="info" />
    </logger>
    

    正确的答案是:我同意这是一条无害的消息,但在我的例子中,我通过将
    @Bean
    声明更改为返回
    任务执行器
    ,而不是基类
    执行器