问题描述
用 Maven 构建的 Spring 3.2.3,尝试使用 @Scheduled 做定时任务,没有生效,但也未报任何错误。环境:pom.xml---------------------------------------------------<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.test</groupId> <artifactId>xyz</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>xyz</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>3.2.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>3.2.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.2.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>3.2.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>3.2.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>3.2.3.RELEASE</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies></project>applicationContext.xml-----------------------------------------------------<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd" default-autowire="byName" default-lazy-init="true"> <context:component-scan base-package="com.test" /> <task:annotation-driven /></beans>测试任务-------------------------------------------------------package com.test.task;import java.util.Date;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;@Componentpublic class MyTask { @Scheduled(cron = "0/5 * * * * ?") public void doSth() { System.out.println(new Date()); }}但是,如果不使用 @Scheduled,用 <task> 标签则任务正常运行:<bean id="myTask" class="com.test.task.MyTask" /><task:scheduled-tasks> <task:scheduled ref="myTask" method="doSth" cron="0/5 * * * * ?" /></task:scheduled-tasks>求解?
解决方案
怀疑 default-lazy-init="true" 惹得祸
解决方案二:
应该这样配置吧<context:component-scan base-package="com.test.task" />