我需要在早上7点05分执行一项任务,但是我收到了一个错误。 这是我创建的控制器。
@Service("myCtr")
public class MyController {
@Autowired
private TaskScheduler scheduler;
@Async
public void executeTaskT() {
scheduler.schedule(new MyWorker(),
new CronTrigger("5 7 * * *"));
}
}
MyWorker正是以这种方式实现Runnable:
[...]
@Override
public void run() {
doWork();
}
private void doWork() { [...]
我的调度程序配置文件由web-application-config.xml导入:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<bean id="TaskScheduler"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler">
<property name="waitForTasksToCompleteOnShutdown" value="true" />
<property name="poolSize" value="1000" />
</bean>
</beans>
错误:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyCtr': Injection
of autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not autowire field: private
org.springframework.scheduling.TaskScheduler [...].MyController.scheduler; nested
exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type
[org.springframework.scheduling.TaskScheduler] found for dependency: expected at least 1 bean which
qualifies as autowire candidate for this dependency. Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true)}
[...]
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private
org.springframework.scheduling.TaskScheduler [...].MyController.scheduler; nested
exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type
[org.springframework.scheduling.TaskScheduler] found for dependency: expected at least 1 bean which
qualifies as autowire candidate for this dependency. Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true)}
[...]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type
[org.springframework.scheduling.TaskScheduler] found for dependency: expected at least 1 bean which
qualifies as autowire candidate for this dependency. Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true)}
答案 0 :(得分:3)
看来Spring找不到你的TaskScheduler
bean。
使用INFO日志记录,您应该能够在初始化期间在日志中找到您的bean定义。如果没有,请确保通过进一步测试有效地读取配置文件。
为了您的确切需要,您还可以使用以下内容:
@Service
public class MyService {
@Scheduled(cron = "0 5 7 * * *")
public void myMethod() { ... }
}
使用此配置:
<task:annotation-driven scheduler="myScheduler"/>
<task:scheduler id="myScheduler" pool-size="1000"/>
假设MyService
被恰当地视为一个bean,使用例如组件扫描。