Java专栏 | ||
---|---|---|
上一篇 | 主目录 | 下一篇 |
【前言】
本文章系列记录第一次实习中 - - 学习笔记 - - Java实现定时发送邮件的任务
1 基础知识
- ApplicationContext事件机制是观察者设计模式的实现,通过ApplicationEvent类和
ApplicationListener
接口(本文项目示例基于这个方式来实现),可以实现ApplicationContext事件处理。 - 如果容器中有一个ApplicationListener Bean,每当ApplicationContext发布ApplicationEvent时,ApplicationListener Bean将自动被触发。这种事件机制都必须需要程序显示的触发。
- 其中spring有一些内置的事件,当完成某种操作时会发出某些事件动作。比如监听ContextRefreshedEvent事件,当所有的bean都初始化完成并被成功装载后会触发该事件,实现
ApplicationListener< ContextRefreshedEvent >
接口可以收到监听动作,然后可以写自己的逻辑。
同样事件可以自定义、监听也可以自定义,完全根据自己的业务逻辑来处理。
参考博文:https://blog.csdn.net/liyantianmin/article/details/81017960
2 项目示例
要实现任务调度(发送邮件)首先需要在springboot项目pom.xml中引入maven依赖(quartz、mail
等),完整如下:
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>