SpringBoot+Mybatis-Plus+Swagger2+Timer

目录

1.什么是SpringBoot及SpringBoot的特点

2.使用Idea创建SpringBoot快速搭建工程

3.SpringBoot常用的配置文件及如何读取配置文件的内容

4.SpringBoot整合数据源

5.SpringBoot整合Mybatis

6.SpringBoot自动装配原理

7.SpringBoot整合Mybatis-Plus

8.SpringBoot整合Swagger2

9.SpringBoot整合定时器-quartz

1.什么是SpringBoot及SpringBoot的特点

1.1什么是SpringBoot

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化Spring应用的初始搭建以及开发过程 . 理解:spring框架搭建的步骤:[1]依赖 [2]配置文件。 使用springboot可以简化上面的两个步骤。

1.2SpringBoot特点

① 创建独立的 Spring 应用程序

② 嵌入的 Tomcat,无需部署 WAR 文件

③ 简化 Maven 配置

④ 自动配置 Spring

⑤ 提供生产就绪型功能,如指标,健康检查和外部配置

⑥ 开箱即用,没有代码生成,也无需 XML 配置。

2.使用Idea创建SpringBoot快速搭建工程

Idea版本:IntelliJ IDEA 2022.2

2.1联网

3.SpringBoot常用的配置文件及如何读取配置文件的内容

3.1SpringBoot常用的配置文件

porperties格式和yml格式 区别是两者书法风格不同

porperties

 server.port=8080
 server.servlet.context-path=/funain

yml

 server:
   port: 8080
   servlet:
     context-path: /funian

不管使用哪个配置文件,他们的名字必须叫application. 如果上面两个配置文件同时存在,而且里面有相同的配置。则properties优先级高于yml优先级。

3.2如何读取配置文件的内容

java为什么需要读取配置文件的内容,我们开发时需要把哪些内容放入配置文件。

OSS:上传文件。accessKeyId,accessKeySecret等,这些内容能写在java源代码中。硬编码文件,不利维护。 我们需要把信息写入配置文件。

读取方式有两种:

第一种方式: 在类上@ConfigurationProperties(prefix="")

 @Data
 @Component
 @ConfigurationProperties(prefix = "student")
 public class Student {
     private String name;
     private Integer age;
     private String address;
     private String[] hobby;
     private Map<String,String> map;
 ​
 }
 student.name=killer
 student.age=18
 student.address=India
 student.hobby[0]=swimming
 student.hobby[1]=skating
 student.hobby[2]=playing
 student.map.word1=hello
 student.map.word2=coming
 student:
   name: killer
   age: 18
   address: India
   hobby:
     - swimming
     - skating
     - playing
   map:
     word1: hello
     word2: coming

第二种使用@Value读取属性:---他只能读取基本类型和String类型。加在属性上

     @Value("${student.name}")
     private String name;

4.SpringBoot整合数据源

这里使用druid数据源

(1) 导入相关依赖

 <!--        导入mysql依赖-->
         <dependency>
             <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>
         </dependency>
 <!--        导入数据源-->
         <dependency>
             <groupId>com.alibaba</groupId>
             <artifactId>druid-spring-boot-starter</artifactId>
             <version>1.2.16</version>
         </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-jdbc</artifactId>
         </dependency>

(2) 配置数据源信息

 spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
 spring.datasource.druid.url=jdbc:mysql://localhost:3306/ssm_db?useSSL=false&serverTimezone=UTC
 spring.datasource.druid.username=root
 spring.datasource.druid.password=123456

(3) 测试

 @SpringBootTest
 class SpringBoot09ApplicationTests {
     @Autowired
     private DataSource dataSource;
     @Test
     public void testDataSource(){
         System.out.println(dataSource);
     }
 }

5.SpringBoot整合Mybatis

(1) 导入相关依赖

 <dependency>
     <groupId>org.mybatis.spring.boot</groupId>
     <artifactId>mybatis-spring-boot-starter</artifactId>
     <version>2.3.0</version>
 </dependency>

(2) 修改配置文件

 #指定映射文件所在路径(默认是以下路径)
 mybatis.mapper-locations=classpath:mapper/*.xml
 #mybatis日志文件
 mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

(3) mapper接口

 public interface BookMapper {
     public List<Book> findAll();
 }

(4) 为mapper接口生成代理实现类

 (5) 测试

 @SpringBootTest
 class SpringBoot09ApplicationTests {
     @Autowired
     private BookMapper bookMapper;
     @Test
     public void testFindAll(){
         List<Book> list = bookMapper.findAll();
         System.out.println(list);
     }
 }

6.SpringBoot自动装配原理

6.1 springboot包扫描原理

包建议大家放在主类所在包或者子包。默认包扫描的是主类所在的包以及子包。

主函数在运行时会加载一个使用@SpringBootApplication标记的类。而该注解是一个复合注解,包含@EnableAutoConfiguration,这个注解开启了自动配置功能。 该注解也是一个复合注解,包含@AutoConfigurationPackage。 该注解中包含@Import({Registrar.class}),这个注解引入Registrar类。该类中存在registerBeanDefinitions,可以获取扫描的包名。

如果需要人为修改扫描包的名称则需要在主类上@ComponentScan(basepackage={"包名"})

6.2 springboot自动装配原理

思考: 有没有自己使用DispatcherServlet. 为什么DispatcherServlet能用。

主函数在运行会执行一个使用@SpringbootApplication注解的类,该注解是一个复合注解,包含@EnableAutoConfiguration, 该注解开启自动配置功能,该注解也是一个复合注解,包含@Import() 该注解需要导入AutoConfigurationImportSelector类。 该类会加载很多自动装配类,而这些自动装配类完成相应的自动装配原理。

7.SpringBoot整合Mybatis-Plus

7.1mybatis-plus概述

MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

我们的愿景是成为 MyBatis 最好的搭档,就像 魂斗罗 中的 1P、2P,基友搭配,效率翻倍。

不能替代mybatis ,以后对于单表操作的所有功能,都可以使用mp完成。但是链表操作的功能还得要校验mybatis.

7.2如何使用mp

(1) 创建一个SpringBoot工程并导入相关依赖

 <?xml version="1.0" encoding="UTF-8"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
     <modelVersion>4.0.0</modelVersion>
     <parent>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-parent</artifactId>
         <version>2.3.12.RELEASE</version>
         <relativePath/> <!-- lookup parent from repository -->
     </parent>
     <groupId>com.funian</groupId>
     <artifactId>SpringBoot_09</artifactId>
     <version>0.0.1-SNAPSHOT</version>
     <name>SpringBoot_09</name>
     <description>SpringBoot_09</description>
     <properties>
         <java.version>1.8</java.version>
     </properties>
     <dependencies>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-web</artifactId>
         </dependency>
 <!--        导入mysql依赖-->
         <dependency>
             <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>
         </dependency>
 <!--        导入mybatis-plus依赖-->
         <dependency>
             <groupId>com.baomidou</groupId>
             <artifactId>mybatis-plus-boot-starter</artifactId>
             <version>3.4.1</version>
         </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-test</artifactId>
             <scope>test</scope>
         </dependency>
         <dependency>
             <groupId>org.projectlombok</groupId>
             <artifactId>lombok</artifactId>
         </dependency>
     </dependencies>
     <build>
         <plugins>
             <plugin>
                 <groupId>org.springframework.boot</groupId>
                 <artifactId>spring-boot-maven-plugin</artifactId>
             </plugin>
         </plugins>
     </build>
 </project>

(2) 配置数据源

 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
 spring.datasource.url=jdbc:mysql://localhost:3306/ssm_db?useSSL=false&serverTimezone=UTC
 spring.datasource.username=root
 spring.datasource.password=123456
 ​
 #指定映射文件所在路径(默认是以下路径)
 mybatis-plus.mapper-locations=classpath:mapper/*.xml
 #mybatis日志文件
 mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

(3) 创建实体类

 @Data
 public class Book implements Serializable {
     @TableId(type = IdType.AUTO) //标明主键 采用递增策略
     private Integer id;
     private String type;
     private String name;    
     private String description;
 }

(4) 为接口生成代理实现类

(5) 测试

 package com.funian;
 ​
 import com.funian.domain.Book;
 import com.funian.mapper.BookMapper;
 import org.junit.jupiter.api.Test;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.test.context.SpringBootTest;
 ​
 import java.util.List;
 ​
 @SpringBootTest
 class SpringBoot09ApplicationTests {
     @Autowired
     private BookMapper bookMapper;
     @Test
     public void testFindAll(){
         List<Book> list = bookMapper.selectList(null);
         System.out.println(list);
     }
 }

7.3使用mp完成CRUD

//分页查询需要配置拦截器

 @Configuration
 @MapperScan(basePackages = "com.funian.mapper")
 public class MybatisPlusConfig {
     /**
      * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
      */
     @Bean
     public MybatisPlusInterceptor mybatisPlusInterceptor() {
         MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
         interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
         return interceptor;
     }
 ​
     @Bean
     public ConfigurationCustomizer configurationCustomizer() {
         return configuration -> configuration.setUseDeprecatedExecutor(false);
     }
 }

//CRUD

 @Test
 public void testCRUD(){
     //根据id查询
     Book book = bookMapper.selectById(1);
     System.out.println(book);
     //增加
     int insert = bookMapper.insert(book);
     System.out.println(insert);
     //更新
     int i = bookMapper.updateById(book);
     System.out.println(i);
     //根据id删除
     int delete = bookMapper.deleteById(14);
     System.out.println(delete);
     List<Integer> list = new ArrayList<>();
     list.add(20);
     list.add(21);
     //批量删除
     bookMapper.deleteBatchIds(list);
     QueryWrapper<Book> qw = new QueryWrapper<>();
     qw.gt("id",5);//条件 >
     qw.like("name","直播");//条件 模糊查询
     //根据条件查询
     List<Book> bookList = bookMapper.selectList(qw);
     System.out.println(bookList);
     //current 当前页码
     //size 数据条数
     IPage<Book> page = new Page<>(1,5);
     //根据条件分页查询
     bookMapper.selectPage(page, qw);
     System.out.println("获取当前页的数据:" +page.getRecords());
     System.out.println("获取总页数:"+page.getPages());
     System.out.println("获取总数据条数:"+page.getTotal());
 }

7.4联表使用mp的分页对象

//mapper接口

 public interface StudentMapper extends BaseMapper<Student> {
     public IPage<Student> selectByPage(IPage<Student> page, @Param("ew") Wrapper<Student> wrapper);
 }

//实体类

 @Data
 @NoArgsConstructor
 @AllArgsConstructor
 public class Student implements Serializable {
 ​
     @TableId(type = IdType.AUTO)
     private Integer sid;
 ​
     private String sname;
 ​
 ​
     private Integer sage;
 ​
     private Integer classid;
 ​
     @TableField(exist = false)
     private Classes classes;
 }

//映射文件.xml

 <?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.funian.mapper.StudentMapper">
 ​
     <resultMap id="BaseResultMap" type="com.funian.domain.entity.Student">
             <id property="sid" column="sid" jdbcType="INTEGER"/>
             <result property="sname" column="sname" jdbcType="VARCHAR"/>
             <result property="sage" column="sage" jdbcType="INTEGER"/>
             <result property="classid" column="classid" jdbcType="INTEGER"/>
         <association property="classes" javaType="com.funian.domain.entity.Classes" autoMapping="true">
             <id property="cid" column="cid" jdbcType="INTEGER"></id>
         </association>
     </resultMap>
 ​
     <sql id="Base_Column_List">
         sid,sname,sage,
         classid,classes.ccurriculum
     </sql>
 ​
     <select id="selectByPage" resultMap="BaseResultMap">
         select <include refid="Base_Column_List"/> from student
             inner join classes on classes.cid = student.classid
                 <if test="ew!=null and ew.sqlSegment!=''">
                     <where>and ${ew.sqlSegment}</where>
                 </if>
     </select>
 </mapper>

//测试

 @Test
 void testSelectByPage() {
     IPage<Student> studentPage = new Page<>();
     QueryWrapper<Student> qw = new QueryWrapper<>();
     qw.gt("sage",20);
     studentMapper.selectByPage(studentPage,qw);
     System.out.println(studentPage.getRecords());
 }

8.SpringBoot整合Swagger2

8.1什么是swagger2

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务的接口文档 . 接口: controller相应的路径方法

8.2为什么是swagger2

目前的项目基本都是前后端分离,后端为前端提供接口的同时,还需同时提供接口的说明文档。但我们的代码总是会根据实际情况来实时更新,这个时候有可能会忘记更新接口的说明文档,造成一些不必要的问题。

8.3如何使用接口文档Swagge2

         <!--swagger2依赖-->
         <dependency>
             <groupId>com.spring4all</groupId>
             <artifactId>swagger-spring-boot-starter</artifactId>
             <version>1.9.1.RELEASE</version>
         </dependency>
         <dependency>
             <groupId>com.github.xiaoymin</groupId>
             <artifactId>swagger-bootstrap-ui</artifactId>
             <version>1.7.8</version>
         </dependency>

(2) 创建一个配置类

 @Component
 public class Swagger2Config {
     @Bean
     public Docket docket(){
         Docket docket = new Docket(DocumentationType.SWAGGER_2).groupName("ruyuan")
                 .apiInfo(getInfo())
                 .select()
                 .apis(RequestHandlerSelectors.basePackage("com.funian.controller")) //只为com.funian.controller包下的类生成接口文档
                 .build();
         return docket;
     }
 ​
     private ApiInfo getInfo(){
         Contact DEFAULT_CONTACT = new Contact("伏念", "http://www.xjent.com/", "110@qq.com");
         ApiInfo apiInfo=new ApiInfo("小圣贤庄API", "小圣贤庄API", "4.1.0", "http://www.baidu.com",
                 DEFAULT_CONTACT, "盘古科技", "https://cn.bing.com/", new ArrayList<VendorExtension>());
         return apiInfo;
     }
 }

(3) 开启swagger2注解驱动

 @SpringBootApplication
 @MapperScan(basePackages = "com.funian.mapper")
 @EnableSwagger2 //开启swagger2
 public class SpringBoot08Application {
 ​
     public static void main(String[] args) {
         SpringApplication.run(SpringBoot08Application.class, args);
     }
 ​
 }

(4) 访问swagger2在线文档

http://ip.port/doc.html

http://ip.port/swagger-ui.html

8.4swagger2常用的注解

使用swagger注解对接口参数加以说明。

@Api(tags="")====使用在controller类上

@ApiOperation(value="")====接口方法上 接口方法加以说明

@ApiParam(value = "",name = "",required = true)

@ApiModel====实体类

@ApiModelProperty===>实体类的属性说明

版本提示:

这里使用springboot 2.3.12.RELEASE

9.SpringBoot整合定时器-quartz

cron在线表达式

定时器: 在指定的时间执行相应的业务代码。

应用场景: 比如: 定时删除OSS中冗余的文件

三十分钟未支付---->取消订单。

定时发送短信---->11.11====>

(1) 导入定时器依赖

 <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-quartz</artifactId>
         </dependency>

(2) 配置定时器任务

 @Component
 public class TimerTasks {
     @Scheduled(cron = "0/5 * * * * ? ")
     public void task01(){
         System.out.println("~~~~~~"+ LocalDateTime.now());
     }
 }

(3) 开启定时器注解驱动

 @SpringBootApplication
 @MapperScan(basePackages = "com.funian.mapper")
 @EnableScheduling //开启定时器
 public class SpringBoot08Application {
 ​
     public static void main(String[] args) {
         SpringApplication.run(SpringBoot08Application.class, args);
     }
 ​
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值