spring的应用 xml配置实现定时任务
定时任务的实现:
通过xml实现:
创建qiuckstart的maven文件
把依赖配置改改 jdk1.8 以及12 再删掉一些不必要的配置
引入spring依赖坐标
和java同一个目录下创建resources 作为 资源根
结构如图:
spring.xml配置:
从官网复制的
Core Technologies
复制完点击自动加载依赖 从而消除报错
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="..." class="..."> (1) (2)<!-- collaborators and configuration for this bean go here --></bean><bean id="..." class="..."><!-- collaborators and configuration for this bean go here --></bean><!-- more bean definitions go here --></beans>
Dao层:
@Repository
Service层:
@Service
Controller层:
@Controller
任意类:
@Component
spring xml里添加此:
<context:component-scan base-package="com.xxxx"/><task:scheduled-tasks><task:scheduled ref="taskJob" method="job1" cron="0/2 * * * * ?"/></task:scheduled-tasks>
测试类:
package com.xxxx;import com.xxxx.task.taskJob;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class Test {public static void main(String[] args) {ApplicationContext ac=new ClassPathXmlApplicationContext("spring.xml");taskJob taskJob=(taskJob)ac.getBean("taskJob");}
}
taskjob 加注解
package com.xxxx.task;import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;@Component
public class taskJob {private SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");public void job1(){System.out.println("任务一"+df.format(new Date()));}
}
中间有报错 是因为下图 cron 参数 少个* 提示里说 需要五个空格 =========》强迫自己看英文报错
通过注解实现:
定义方法时加上一行注解:
@Scheduled(cron=....)
配置文件 只需要改一行 :
<task:annotation-driven/>
如图:
正常调用方法
运行如图:
自我总结:
定时任务只是一个标签 里面参数自己设置
方法写好即可
各文件作用:
方法类:写方法(不用创建对象)
spring:作用是代方法创建对象
测试类:写测试 (通过ClassPathXmlApplicationContext来创建spring对象)