学习视频链接,以示尊重:https://www.bilibili.com/video/BV1PE411i7CV?p=51
一、SpringBoot整合MyBatis
1、导入 MyBatis 所需要的依赖:
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
2、配置数据库连接信息(和上一节所学SpringBoot继承Druid所配置信息相同)
3、创建实体类:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Department {
private Integer id;
private String departmentName;
}
4、创建mapper目录以及对应的 Mapper 接口:
//@Mapper : 表示本类是一个 MyBatis 的 Mapper
@Mapper
@Repository
public interface DepartmentMapper {
// 获取所有部门信息
List<Department> getDepartments();
// 通过id获得部门
Department getDepartment(Integer id);
}
5、对应地Mapper映射文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com..xingyu.springbootlearn.mapper.DepartmentMapper">
<select id="getDepartments" resultType="Department">
select * from department;
</select>
<select id="getDepartment" resultType="Department" parameterType="int">
select * from department where id = #{id};
</select>
</mapper>
或者直接使用注解:
@Mapper
@Repository
public interface DepartmentMapper {
// 获取所有部门信息
@Select("select * from department")
List<Department> getDepartments();
// 通过id获得部门
@Select("select * from department where id = #{id}")
Department getDepartment(@Param("id") Integer id);
}
6、在application.yaml 全局配置文件中配置mybatis:
mybatis:
type-aliases-package: com.xingyu.springbootlearn.pojo
mapper-locations: classpath:mybatis/mapper/*.xml
configuration:
map-underscore-to-camel-case: true
7、maven配置资源过滤问题
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
8、编写Controller进行测试:
@RestController
public class DeptController {
@Autowired
private DepartmentMapper departmentMapper;
@GetMapping("/getLists")
public List<Department> getDepartments(){
List<Department> departments = departmentMapper.getDepartments();
for (Department d: departments) {
System.out.println(d);
}
return departments;
}
@GetMapping("/getList/{id}")
public Department getDepartment(@PathVariable("id") int id){
return departmentMapper.getDepartment(id);
}
}
二、异步任务
在我们的工作中,常常会用到异步处理任务,SpringBoot都给提供了对应的支持,上手使用十分的简单,只需要开启一些注解支持,配置一些配置文件即可!
1、创建一个service包
2、创建一个类AsyncService
异步处理还是非常常用的,比如我们在网站上发送邮件,后台会去发送邮件,此时前台会造成响应不动,直到邮件发送完毕,响应才会成功,所以我们一般会采用多线程的方式去处理这些任务。
编写方法,假装正在处理数据,使用线程设置一些延时,模拟同步等待的情况;
@Service
public class AsyncService {
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("业务进行中....");
}
}
3、编写Controller 进行测试,这时发现,需要等待3秒后才出现success,这是同步等待的情况:
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@GetMapping("/hello")
public String hello(){
asyncService.hello();
return "success";
}
}
4、为了进行异步处理,在方法上加一个简单的注解 @Async 即可:
//告诉Spring这是一个异步方法
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("业务进行中....");
}
SpringBoot就会自己开一个线程池,进行调用。
5、但是要让这个注解生效,还需要在主程序上添加一个注解@EnableAsync ,开启异步注解功能:
@EnableAsync //开启异步注解功能
@SpringBootApplication
public class SpringbootTaskApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootTaskApplication.class, args);
}
}
三、定时任务
项目开发中经常需要执行一些定时任务,比如需要在每天凌晨的时候,分析一次前一天的日志信息,Spring 为我们提供了异步执行任务调度的方式,提供了:
-
两个接口:
- TaskExecutor接口
- TaskScheduler接口
-
两个注解:
- @EnableScheduling
- @Scheduled
1、创建一个ScheduledService,里面存在一个hello方法,他需要定时执行,则进行如下处理:
@Service
public class ScheduledService {
//秒 分 时 日 月 周几
//0 * * * * MON-FRI
//注意cron表达式的用法;
@Scheduled(cron = "0 * * * * 0-7")
public void hello(){
System.out.println("hello.....");
}
}
2、这里写完定时任务之后,需要在主程序上增加@EnableScheduling 开启定时任务功能:
@EnableAsync //开启异步注解功能
@EnableScheduling //开启基于注解的定时任务
@SpringBootApplication
public class SpringbootTaskApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootTaskApplication.class, args);
}
}
这里的 cron 表达式的语法需要注意,但是也有 cron 表达式自动生成器:http://www.bejson.com/othertools/cron/
4、常用的表达式
(1)0/2 * * * * ? 表示每2秒 执行任务
(1)0 0/2 * * * ? 表示每2分钟 执行任务
(1)0 0 2 1 * ? 表示在每月的1日的凌晨2点调整任务
(2)0 15 10 ? * MON-FRI 表示周一到周五每天上午10:15执行作业
(3)0 15 10 ? 6L 2002-2006 表示2002-2006年的每个月的最后一个星期五上午10:15执行作
(4)0 0 10,14,16 * * ? 每天上午10点,下午2点,4点
(5)0 0/30 9-17 * * ? 朝九晚五工作时间内每半小时
(6)0 0 12 ? * WED 表示每个星期三中午12点
(7)0 0 12 * * ? 每天中午12点触发
(8)0 15 10 ? * * 每天上午10:15触发
(9)0 15 10 * * ? 每天上午10:15触发
(10)0 15 10 * * ? 每天上午10:15触发
(11)0 15 10 * * ? 2005 2005年的每天上午10:15触发
(12)0 * 14 * * ? 在每天下午2点到下午2:59期间的每1分钟触发
(13)0 0/5 14 * * ? 在每天下午2点到下午2:55期间的每5分钟触发
(14)0 0/5 14,18 * * ? 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
(15)0 0-5 14 * * ? 在每天下午2点到下午2:05期间的每1分钟触发
(16)0 10,44 14 ? 3 WED 每年三月的星期三的下午2:10和2:44触发
(17)0 15 10 ? * MON-FRI 周一至周五的上午10:15触发
(18)0 15 10 15 * ? 每月15日上午10:15触发
(19)0 15 10 L * ? 每月最后一日的上午10:15触发
(20)0 15 10 ? * 6L 每月的最后一个星期五上午10:15触发
(21)0 15 10 ? * 6L 2002-2005 2002年至2005年的每月的最后一个星期五上午10:15触发
(22)0 15 10 ? * 6#3 每月的第三个星期五上午10:15触发
四、邮件任务
邮件发送,在我们的日常开发中,也非常的多,Springboot也帮我们做了支持:
- 邮件发送需要引入spring-boot-start-mail
- SpringBoot 自动配置MailSenderAutoConfiguration
- 定义MailProperties内容,配置在application.yml中
- 自动装配JavaMailSender
- 测试邮件发送
具体使用:
1、引入pom依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、编写application.yaml 配置文件进行配置:
spring:
mail:
username: [email protected]
password: XXXXXXXXXXXXXXXX
host: smtp.qq.com
smtp:
socketFactory:
class: javax.net.ssl.SSLSocketFactory
properties:
mail:
smtp:
ssl:
enable: true
其中的 password 是授权码。
获取授权码的方式:在QQ邮箱中的设置->账户->开启pop3和smtp服务
3、测试:
package com.xingyu.springbootlearn;
import com.alibaba.druid.pool.DruidDataSource;
import com.xingyu.springbootlearn.pojo.Dog;
import com.xingyu.springbootlearn.pojo.Person;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.sql.DataSource;
import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
@SpringBootTest
class SpringbootLearnApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
public void contextLoads() {
//邮件设置1:一个简单的邮件
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("通知-今年国庆节不放假!");
message.setText("今晚九点开会商讨工作!");
message.setTo("[email protected]");
message.setFrom("[email protected]");
mailSender.send(message);
}
@Test
public void contextLoads2() throws MessagingException {
//邮件设置2:一个复杂的邮件
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setSubject("通知-今年国庆节不放假!");
helper.setText("<b style='color:red'>今晚九点开会商讨工作!</b>",true);
//发送附件
helper.addAttachment("1.png",new File("src/test/java/com/xingyu/springbootlearn/1.png"));
helper.addAttachment("2.png",new File("src/test/java/com/xingyu/springbootlearn/2.png"));
helper.setTo("[email protected]");
helper.setFrom("[email protected]");
mailSender.send(mimeMessage);
}
}