task-spring.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:p="http://www.springframework.org/schema/p" 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"> <!-- 开启定时器注解扫描 --> <task:annotation-driven/> <context:annotation-config/> <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> <context:component-scan base-package="com.demo.service"/> </beans> |
在spring.xml的主配置文件引入
<!-- 通过xml引入获取 定时器xml文件配置 --> <import resource="spring-task.xml"/> |
在Service接口
package com.demo.service; public interface SpringTimer { void testTask(); } |
在Service实现类
package com.demo.service.impl; import org.springframework.context.annotation.PropertySource; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import com.demo.service.SpringTimer; /** spring的@Scheduled注解 需要写在实现上; 定时器的任务方法不能有返回值; 实现类上要有组件的注解@Component,@Service,@Repository * @author chao * */ /* 方式1:加载 properties文件(注解) @PropertySource("classpath:conf/task.properties") 通过注解加载properties 方式2:加载 properties文件(xml) 单个 <context:property-placeholder location="classpath:conf/jdbc.properties"/> 多个 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <!-- 支持多种寻址方式:file classpath --> <value>classpath:conf/task.properties</value> <value>classpath:conf/jdbc.properties</value> </list> </property> </bean> */ @Service public class SpringTimerImpl implements SpringTimer { @Scheduled(cron="${jobs.schedule}") //每5秒执行一次 public void testTask() { System.out.println("我是Spring定时器,执行任务一次..."); } } |