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/beans
        https://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对象)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值