SpringBoot快速入门

守听  金牌会员 | 2022-9-16 17:13:04 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 884|帖子 884|积分 2652

1.1 快速构建-官方脚手架

- 新建模块,新建好之后项目整合就好了。




- 编写业务代码,`Controller`
  1. package com.itheima.web.controller;
  2. import org.springframework.web.bind.annotation.GetMapping;
  3. import org.springframework.web.bind.annotation.PathVariable;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.RestController;
  6. /**
  7. * 用户控制器类
  8. *
  9. * @Author Vsunks.v
  10. * @Blog blog.sunxiaowei.net/996.mba
  11. * @Description: 用户控制器类
  12. */
  13. @RestController
  14. @RequestMapping("/users")
  15. public class UserController {
  16.     // Handler
  17.     @GetMapping("/{id}")
  18.     public String save(@PathVariable Integer id){
  19.         System.out.println("id = " + id);
  20.         return "save success";
  21.     }
  22. }
复制代码
1.2 SpringBoot工程启动

只需要找到启动类的main方法,运行即可只需要找到启动类的main方法,运行即可

2 概念

作用:为了快速开发Spring项目:简化配置 ,简化依赖引入。
Spring的缺点:配置繁琐、依赖繁琐。
可以使用SpringBoot的自动配置和场景启动器(起步依赖)克服上述缺点。
SpringBoot提供了一种快速使用Spring的方式,基于约定优于配置的思想。不需要关注配置,重点关注业务逻辑开发,缩短了项目周期。
SpringBoot实现了0配置,1个依赖完成项目搭建。
SpringBoot通过两点实现了上述效果:

  • 自动配置
    内部提供了大量默认配置,按照约定方式编码即可
  • 起步依赖
    针对不同的场景封装了启动器,比如:web场景启动器中引入了所有web需要的依赖,我们只需要引入web场景启动器坐标即可。
SpringBoot还提供了一些嵌入式web服务器、安全、指标、健康监测、外部配置等。
注意:SpringBoot只是提供了一种快速开发Spring项目的方式,而非对Spring功能上的增强。


2.2 起步依赖

又名场景启动器
2.2.1 使用

起步依赖,就是依赖。可以理解为一个依赖组,一组依赖。
像导入普通依赖一样,导入即可。
2.2.2 原理


  • starter

    • SpringBoot中常见项目名称,定义了当前项目使用的所有项目坐标,以达到减少依赖配置的目的
      1. <?xml version="1.0" encoding="UTF-8"?>
      2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      3.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
      4.     <modelVersion>4.0.0</modelVersion>
      5.     <parent>
      6.         <groupId>org.springframework.boot</groupId>
      7.         <artifactId>spring-boot-starter-parent</artifactId>
      8.         <version>2.5.0</version>
      9.     </parent>
      10.     <groupId>com.itheima</groupId>
      11.     <artifactId>springboot-01-quickstart</artifactId>
      12.     <version>0.0.1-SNAPSHOT</version>
      13.     <dependencies>
      14.         <dependency>
      15.             <groupId>org.springframework.boot</groupId>
      16.             <artifactId>spring-boot-starter-web</artifactId>
      17.         </dependency>
      18.     </dependencies>
      19. </project>
      复制代码
      1. <project xmlns="http://maven.apache.org/POM/4.0.0"
      2.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
      3.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      4.     <modelVersion>4.0.0</modelVersion>
      5.     <groupId>org.springframework.boot</groupId>
      6.     <artifactId>spring-boot-dependencies</artifactId>
      7.     <version>2.5.0</version>
      8.     <packaging>pom</packaging>
      9.     <properties>
      10.         <servlet-api.version>4.0.1</servlet-api.version>        
      11.         ...
      12.     </properties>
      13. </project>
      复制代码

  • 实际开发

    • 使用任意坐标时,仅书写GAV中的G和A,V由SpringBoot提供
    • 如发生坐标错误,再指定version(要小心版本冲突)
      1. <dependency>
      2.     <groupId>junit</groupId>
      3.     <artifactId>junit</artifactId>
      4.     <version>${junit.version}</version>
      5. </dependency>
      6. <dependency>
      7.     <groupId>javax.servlet</groupId>
      8.     <artifactId>javax.servlet-api</artifactId>
      9.     <version>${servlet-api.version}</version>
      10. </dependency>
      复制代码
      1. <?xml version="1.0" encoding="UTF-8"?>
      2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      3.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
      4.     <parent>
      5.         <groupId>org.springframework.boot</groupId>
      6.         <artifactId>spring-boot-starter-parent</artifactId>
      7.         <version>2.5.0</version>
      8.     </parent>
      9.     <dependencies>
      10.         <dependency>
      11.             <groupId>org.springframework.boot</groupId>
      12.             <artifactId>spring-boot-starter-web</artifactId>
      13.         </dependency>
      14.         <dependency>
      15.             <groupId>org.springframework.boot</groupId>
      16.             <artifactId>spring-boot-starter-test</artifactId>
      17.             <scope>test</scope>
      18.         </dependency>
      19.     </dependencies>
      20. </project>
      复制代码

2.2.3 切换web容器


  • Jetty比Tomcat更轻量级,可扩展性更强(相较于Tomcat),谷歌应用引擎(GAE)已经全面切换为Jetty
  1. <dependencies>
  2.     <dependency>
  3.         <groupId>org.springframework.boot</groupId>
  4.         <artifactId>spring-boot-starter-web</artifactId>
  5.         
  6.         <exclusions>
  7.             <exclusion>
  8.                 <groupId>org.springframework.boot</groupId>
  9.                 <artifactId>spring-boot-starter-tomcat</artifactId>
  10.             </exclusion>
  11.         </exclusions>
  12.     </dependency>
  13.    
  14.     <dependency>
  15.         <groupId>org.springframework.boot</groupId>
  16.         <artifactId>spring-boot-starter-jetty</artifactId>
  17.     </dependency>
  18. </dependencies>
复制代码
3. 配置

3.1 配置文件分类

SpringBoot支持yml/yaml和properties等格式的配置文件。
按照约定,配置文件的文件名为application.xxx
三种配置文件的优先级:properties > yml > yaml,
多个配置(文件)中配置了相同的key,优先级高的生效;多个配置(文件)中配置了不同的key,同时生效。
示例如下:

  • properties
    1. server.port=8080
    复制代码
  • xml(SpringBoot不支持)
    1. <server>
    2.     <port>8080</port>
    3. </server>
    复制代码
  • yml/yaml-简洁,层次结构清晰,以数据为核心(推荐)
    1. server:
    2.   port: 8080
    复制代码
3.2 yml 语法


  • 大小写敏感
  • 数据值前边必须有空格,作为分隔符
  • 行头使用缩进表示层级关系
  • 缩进时不允许使用Tab键,只允许使用空格(各个系统 Tab对应的 空格数目可能不同,导致层次混乱)。
  • 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
  • # 表示单行注释,从这个字符一直到行尾,都会被解析器忽略。
    1. # 这是一行注释
    2. lesson: SpringBoot
    3. server:
    4.   port: 80
    复制代码
  • 数组:一组按次序排列的值,使用 “ - ”表示数组每个元素
    1. lesson: SpringBoot
    2. server:
    3.   port: 80
    4. enterprise:
    5.   name: itcast
    6.   age: 16
    7.   tel: 4006184000
    8.   subject:
    9.     - Java
    10.     - 前端
    11.     - 大数据
    复制代码
3.3.1 封装全部数据到Environment对象


  • 获取方式
    首先在当前类中注入Environment对象,然后通过该对象的getProperty(“key”)方法获取对应的值
  • 关系图示


  • Yaml文件
    1. lesson: SpringBoot
    2. server:
    3.   port: 80
    4. enterprise:
    5.   name: itcast
    6.   age: 16
    7.   tel: 4006184000
    8.   subject:
    9.     - Java
    10.     - 前端
    11.     - 大数据
    复制代码
  • 读取代码
    1. @RestController
    2. @RequestMapping("/books")
    3. public class BookController {
    4.     //使用Environment封装全配置数据
    5.     @Autowired
    6.     private Environment environment;
    7.     @GetMapping("/{id}")
    8.     public String getById(@PathVariable Integer id){
    9.         System.out.println(environment.getProperty("lesson"));
    10.         System.out.println(environment.getProperty("server.port"));
    11.         System.out.println(environment.getProperty("enterprise.age"));
    12.         System.out.println(environment.getProperty("enterprise.subject[1]"));
    13.         return "hello , spring boot!";
    14.     }
    15. }
    复制代码
3.3.2自定义对象封装指定数据


  • 映射图示
<img scr="https://img2022.cnblogs.com/blog/2944646/202208/2944646-20220808175129207-1821647711.png">

  • Yaml文件
    1. lesson: SpringBoot
    2. server:
    3.   port: 80
    4. enterprise:
    5.   name: itcast
    6.   age: 16
    7.   tel: 4006184000
    8.   subject:
    9.     - Java
    10.     - 前端
    11.     - 大数据
    复制代码
  • 准备实体类
    1. @Data
    2. // 装配进Spring容器
    3. @Component
    4. // 添加注解,并指定访问前缀。前缀与配置文件中对应的一级属性名一致
    5. @ConfigurationProperties(prefix = "enterprise")
    6. public class Enterprise {
    7.     // 实体类中成员变量名和二级属性名一致
    8.     private String name;
    9.     private Integer age;
    10.     private String tel;
    11.     private String[] subject;
    12. }
    复制代码
  • 读取代码
    1. @RestController
    2. @RequestMapping("/books")
    3. public class BookController {
    4.         // 注入Enterprise,该对象就读取了配置文件,并封装配置文件属性到该对象中。
    5.     @Autowired
    6.     private Enterprise enterprise;
    7.     @GetMapping("/{id}")
    8.     public String getById(@PathVariable Integer id){
    9.         System.out.println(enterprise);
    10.         return "hello , spring boot!";
    11.     }
    12. }
    复制代码
  • 自定义对象封装数据警告且无提示的问题


  • 解决方案(配置依赖)
    1. <dependency>
    2.     <groupId>org.springframework.boot</groupId>
    3.     <artifactId>spring-boot-configuration-processor</artifactId>
    4.     <optional>true</optional>
    5. </dependency>
    复制代码
3.4 多环境

在实际开发中,项目的开发环境测试环境生产环境的配置信息不一致。SpringBoot支持快速切换。
3.4.1 多环境配置并启用

3.4.1.1 yaml文件多环境


  • yaml单文件多文件


  • 演示配置文件(单位件多文档)
    1. #设置启用的环境
    2. spring:
    3.   profiles:
    4.     active: dev
    5. ---  #文档分隔线,上下分别表示不同的文档
    6. #开发。
    7. # 高版本的springBoot中,spring.profiles:文档名 的命名方式已经被标记为过时
    8. # 推荐使用 spring.config.activate.on=profile:文档名 的命名方式
    9. # 激活方式保持不变
    10. spring:
    11.   config:
    12.     activate:
    13.       on-profile: dev
    14. server:
    15.   port: 80
    16. ---
    17. #生产
    18. spring:
    19.   profiles: pro
    20. server:
    21.   port: 81
    22. ---
    23. #测试
    24. spring:
    25.   profiles: test
    26. server:
    27.   port: 82
    28. ---
    复制代码
注意:


  • 为文档命名的方式,在不同的SpringBoot版本中会稍有差异
    低版本中只支持:spring.profiles:文档名
    高版本还支持并推荐使用:spring.config.activate.on=profile:文档名
  • 默认激活方式保持不变。

3.4.2 总结

不要记,配置的时候,最终要的是结果;只要结果符合预期,怎么配置都可以。
想了解配置细节规则,可以查看官网文档。
4. 整合其他技术

最终目的是为了能够完成SSM的整合

  • SpringBoot整合Spring(不需要)
  • SpringBoot整合SpringMVC(导入web起步依赖)
  • SpringBoot整合MyBatis(主要)
4.1 整合Mybatis

4.1.1 对比Spring整合Mybatis


  • 配置一对依赖
  • SpringConfig配置类
  • JdbcConfig配置类

    • 定义数据源(加载properties配置项:driver、url、username、password)

  • MyBatisConfig配置类

    • 定义SqlSessionFactoryBean
    • 定义MapperScannerConfigurer

4.1.2 SpringBoot整合Mybatis


  • 新建SpringBoot模块
  • 导入一个起步依赖
  • 配置文件中配置连接四要素
相同的步骤:


  • 编写dao层接口和SQL语句
4.1.3 代码演示


  • 新建SpringBoot项目
  • 配置起步依赖,及MySQL数据库驱动和Druid数据源
    1. <dependency>
    2.     <groupId>org.mybatis.spring.boot</groupId>
    3.     <artifactId>mybatis-spring-boot-starter</artifactId>
    4.     <version>2.2.2</version>
    5. </dependency>
    6. <dependency>
    7.     <groupId>mysql</groupId>
    8.     <artifactId>mysql-connector-java</artifactId>
    9.     <version>5.1.48</version>
    10. </dependency>
    11. <dependency>
    12.     <groupId>com.alibaba</groupId>
    13.     <artifactId>druid</artifactId>
    14.     <version>1.1.16</version>
    15. </dependency>
    复制代码
  • 配置数据源参数(主要是连接四要素)
    1. server:
    2.   port: 80
    3. spring:
    4.   # 配置连接池参数
    5.   datasource:
    6.     # 连接四要素
    7.     driver-class-name: com.mysql.jdbc.Driver
    8.     url: jdbc:mysql:///ssm_spring
    9.     username: root
    10.     password: root
    11.     # 数据源类型,值为对应的数据源全类名
    12.     type: com.alibaba.druid.pool.DruidDataSource
    复制代码
  • 编写Dao接口和SQL语句
    1. package com.itheima.dao;
    2. import com.itheima.entity.Book;
    3. import org.apache.ibatis.annotations.Select;
    4. /**
    5. * Book持久层接口
    6. *
    7. * @Author Vsunks.v
    8. * @Blog blog.sunxiaowei.net/996.mba
    9. * @Description: Book持久层接口
    10. */
    11. // @Mapper // 把该接口的代理对象装配进Spring(Boot)容器 和@MapperScan二选一即可
    12. public interface BookDao {
    13.     @Select("select * from ssm_spring.t_book where id= #{id}")
    14.     public Book selectById(Integer id);
    15. }
    复制代码
  • 装配Dao进Spring(Boot)容器(启动类上开启Mapper扫描)
    1. package com.itheima;
    2. import org.mybatis.spring.annotation.MapperScan;
    3. import org.springframework.boot.SpringApplication;
    4. import org.springframework.boot.autoconfigure.SpringBootApplication;
    5. /**
    6. * 整合其他技术的启动类
    7. *
    8. * @Author Vsunks.v
    9. * @Blog blog.sunxiaowei.net/996.mba
    10. * @Description: 整合其他技术的启动类
    11. */
    12. @SpringBootApplication
    13. @MapperScan("com.itheima.dao")  // 扫描指定位置的mapper接口,一劳永逸
    14. public class IntegrateApplication {
    15.     public static void main(String[] args) {
    16.         SpringApplication.run(IntegrateApplication.class,args);
    17.     }
    18. }
    复制代码
4.2 整合Junit

4.2.1 步骤说明


  • 新建SpringBoot模块
  • 导入起步依赖(脚手架方式创建的模块会自动添加)
  • 在主包下编写测试入口类(脚手架方式创建的模块会自动添加)
4.2.2 代码演示


  • 新建SpringBoot模块
  • 导入起步依赖(脚手架方式创建的模块会自动添加)
    1. <dependency>
    2.     <groupId>org.springframework.boot</groupId>
    3.     <artifactId>spring-boot-starter-test</artifactId>
    4.     <scope>test</scope>
    5. </dependency>
    复制代码
  • 在主包下编写测试入口类(脚手架方式创建的模块会自动添加)
    1. package com.itheima.test;
    2. import com.itheima.IntegrateApplication;
    3. import com.itheima.dao.BookDao;
    4. import com.itheima.entity.Book;
    5. // import org.junit.Test; // junit4
    6. import org.junit.jupiter.api.Test;  // Junit4
    7. // import org.junit.runner.RunWith;
    8. import org.springframework.beans.factory.annotation.Autowired;
    9. import org.springframework.boot.test.context.SpringBootTest;
    10. import org.springframework.test.context.junit4.SpringRunner;
    11. /**
    12. * BookDao测试类
    13. *
    14. * @Author Vsunks.v
    15. * @Date 2022/8/5 16:48
    16. * @Blog blog.sunxiaowei.net/996.mba
    17. * @Description: BookDao测试类
    18. */
    19. // @RunWith(SpringRunner.class)    // 使用junit4  需要配置该运行器
    20. // 标注该类是一个SpringBoot中的测试类,该类要放在主包下
    21. // 如果不在主包下,需要通过其classes属性指定启动类的字节码对象
    22. @SpringBootTest
    23. public class BookDaoTest {
    24.     // 测谁就注入谁
    25.     @Autowired
    26.     BookDao bookDao;
    27.     // 测试
    28.     @Test
    29.     public void testSelectById(){
    30.         Book book = bookDao.selectById(14);
    31.         System.out.println("book = " + book);
    32.     }
    33. }
    复制代码
4.3 整合SpringMVC

配置起步依赖即可。
4.3.1 实现步骤


  • 配置Web异步依赖
  • 编写Controller
4.3.2 代码演示


  • BookController
    1. package com.itheima.web.controller;
    2. import com.itheima.entity.Book;
    3. import com.itheima.service.BookService;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.web.bind.annotation.GetMapping;
    6. import org.springframework.web.bind.annotation.PathVariable;
    7. import org.springframework.web.bind.annotation.RequestMapping;
    8. import org.springframework.web.bind.annotation.RestController;
    9. /**
    10. * Book控制器类
    11. *
    12. * @Author Vsunks.v
    13. * @Blog blog.sunxiaowei.net/996.mba
    14. * @Description: Book控制器类
    15. */
    16. @RestController
    17. @RequestMapping("/books")
    18. public class BookController {
    19.     @Autowired
    20.     BookService bookService;
    21.     // 根据id查询
    22.     @GetMapping("/{id}")
    23.     public Book getById(@PathVariable Integer id) {
    24.         return bookService.getById(id);
    25.     }
    26. }
    复制代码

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

守听

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表