新建一个Java工程,导入要用到的包,Spring3.2、Quartz2.2.1、aopalliance-1.0.jar、commons-logging-1.2.jar。整个工程目录如下:
package com.mucfc; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** *事件类,基于Spring注解方式 *作者 林炳文(ling20081005@126.com 博客:http://blog.csdn.net/evankaka) *时间 2015.4.29 */ @Component public class MyJob { public MyJob(){ System.out.println("MyJob创建成功"); } @Scheduled(cron = "0/1 * * * * ? ")//每隔1秒隔行一次 public void run(){ System.out.println("Hello MyJob "+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ").format(new Date())); } }2、首先要配置我们的beans.xml,在xmlns 多加下面的内容
xmlns:task="http://www.springframework.org/schema/task"3、然后xsi:schemaLocation多加下面的内容
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
4、最后是我们的task任务扫描注解
<!--开启这个配置,spring才能识别@Scheduled注解--> <task:annotation-driven/>5、自动配置扫描位置:
<!-- 自动扫描注解的bean --> <context:component-scan base-package="com.mucfc"/>6、整个文档如下
<?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:p="http://www.springframework.org/schema/p" 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.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"> <!--开启这个配置,spring才能识别@Scheduled注解--> <task:annotation-driven/> <!-- 自动扫描注解的bean --> <context:component-scan base-package="com.mucfc"/> </beans>7、使用
package com.mucfc; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml"); } }
输出结果:
原文地址:http://blog.csdn.net/evankaka/article/details/45400781