栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot 学习笔记

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力
一、概述 1、SpringBoot 的优、缺点

优点:

  • 创建独立的 Spring 应用
  • 内嵌 Web 服务器
  • 自动 starter 依赖,简化配置
  • 自动配置 Spring 和 第三方功能
  • 提供生产级别的监控、健康检查及外部化配置
  • 无代码生成、无需编写XML
  • SpringBoot是整合 Spring 技术栈的一站式框架
  • SpringBoot是简化 Spring 技术栈的快速开发脚手架

缺点:

  • 人称版本帝,迭代快,需要时刻关注变化
  • 封装太深,内部原理复杂,不容易精通
2、SpringBoot 入门 2.1 环境要求
  • Java 8 及以上
  • Maven 3.3 及以上
  • Intelli IDEA 2019.1.2 及以上
2.2 搭建 SpringBoot 应用
  • 新建一个普通的 maven 工程
  • 引入依赖
    
        org.springframework.boot
        spring-boot-starter-parent
        2.6.7
    
    
    
    	
    		org.springframework.boot
    		spring-boot-starter-web
    	
    
    
  • 创建主程序
    @SpringBootApplication
    public class MainApplication {
        public static void main(String[] args) {
            SpringApplication.run(MainApplication.class, args);
        }
    }
    
  • 编写业务代码
    @RestController
    public class HelloController {
        @RequestMapping("/hello")
        public String handle01(){
            return "Hello, Spring Boot!";
        }
    }
    
  • 运行&测试
    ① 运行MainApplication类
    ② 浏览器访问http://localhost:8888/hello,页面输出Hello, Spring Boot!
    OK,大功告成!
二、深入学习 SpringBoot 1、依赖管理
  • 父项目做依赖管理
    在 pom.xml 中引入了如下父项目:
    
    	org.springframework.boot
    	spring-boot-starter-parent
    	2.3.4.RELEASE
    
    
    上面的父项目又引入了如下父项目,在该项目中声明了几乎所有开发中常用依赖的版本号,所以在引入依赖时不必再声明版本号:
    
    	org.springframework.boot
    	spring-boot-dependencies
    	2.3.4.RELEASE
    
    
  • 场景启动器(starter)
    在 pom.xml 中引入了 web 场景启动器:
    
    	
    		org.springframework.boot
    		spring-boot-starter-web
    	
    
    
    在开发中,只要引入了某个场景的 starter,则该场景需要的所有常规依赖都会自动引入。
    spring-boot-starter-* :表示Spring官方的场景启动器。
    *-spring-boot-starter : 表示第三方场景启动器。
  • 修改依赖默认版本号
    在最底层父项目 spring-boot-dependencies 中,可以查看当前依赖版本用的 key。若要修改,可在当前项目的 pom.xml 中添加以下内容:
    
    
        11
        3.8.0
    
    
2、自动配置
  • 自动配好 Tomcat 服务器
  • 自动配好 SpringMVC
  • 自动配好 Web 常见功能(如字符编码问题)
  • 自动开启组件扫描:
    ① 默认扫描主程序所在包及其下面的所有子包
    ② 自定义包扫描路径:@SpringBootApplication(scanBasePackages=“com.xxx”)
  • 自动配置默认值:
    ① 默认配置最终都是映射到某个类上,如DataSourceProperties
    ② xxxProperties 自动绑定配置文件中配置的值(在 SpringBoot 中,只需在 resource 目录下创建一个 application.properties 配置文件,即可完成所有的配置)
  • 按需加载所有的配置项:
    ① 引入了哪个场景的 starter,这个场景的自动配置才会开启
    ② 可在 spring-boot-autoconfigure 包里查看所有的自动配置功能
3、底层注解 3.1 @Configuration
  • 作用:表示当前类是一个配置类,会自动注册到 Ioc 容器中。
  • 举例:
    @Configuration
    public class MyConfig {
        @Bean
        public User user(){
            User user= new User("Tom", 18);
            return user;
        }
    }
    

    @Bean 注解:表示当前方法的返回值会被注册到 Ioc 容器中,方法名作为组件 id,且如果该方法有形参,会自动从 Ioc 容器中找到对应的实例注入。

  • proxyBeanMethods:代理 Bean 方法
    • @Configuration 注解可通过设置 proxyBeanMethods 的值,控制被 @Bean 标注的方法返回的是单实例还是多实例。
    • @Configuration(proxyBeanMethods = true):默认值,表示开启代理 Bean 方法,此时 @Bean 方法每次返回的都是同一个实例,该模式称为 Full 模式。
    • @Configuration(proxyBeanMethods = false):表示不开启代理 Bean 方法,此时 @Bean 方法每次返回的都是一个新的实例,该模式称为 Lite 模式。

    如何选用:
    ① 配置类组件之间无依赖关系时,用 Lite 模式可以加速容器启动过程
    ② 配置类组件之间有依赖关系时,用 Full 模式

3.2 @Import
  • 举例:@Import({User.class, DBHelper.class})
  • 作用:在 Ioc 容器中自动创建出这两个类型的组件,默认组件的名字就是全类名
3.3 @Conditional
  • 标注范围:类、方法
  • 作用:条件装配,当满足条件时,类或方法才生效
3.3 @ImportResource
  • 作用:将原 Spring 配置文件 bean.xml 中配置的 bean 注册到 Ioc 容器中
  • 举例:
    bean.xml
    
    
        
            
            
        
    
    
    导入:
    @ImportResource("classpath:beans.xml")
    public class MyConfig {
    	...
    }
    
3.4 @ConfigurationProperties
  • 作用:将自定义 bean 类与 application.properties 绑定,实现通过配置文件配置该 bean 类的相关属性。
  • 举例:
    @Component // 需要把该类注册到 Ioc 容器中
    @ConfigurationProperties(prefix = "mycar") //设置该类在配置文件中的前缀
    public class Car {
    	private String brand;
    	private Integer price;
    }
    
    在 application.properties 中就可以配置相关属性值:
    mycar.brand = BYD
    mycar.price = 100000
    

    另一种配置绑定方式:@ConfigurationProperties + @EnableConfigurationProperties

    @ConfigurationProperties(prefix = "mycar") //设置该类在配置文件中的前缀
    public class Car {
    	private String brand;
    	private Integer price;
    }
    
    @EnableConfigurationProperties(Car.class)
    public class MyConfig {
    	...
    }
    
3.5 @SpringBootApplication
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
    ...
}

标志当前类是 SpringBoot 启动类,重点关注其中的 @SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan。

  • @SpringBootConfiguration:标识当前类是 SpringBoot 配置类。
  • @ComponentScan:开启组件扫描。
  • @EnableAutoConfiguration:开启自动配置,重点关注其中的 @AutoConfigurationPackage、@Import(AutoConfigurationImportSelector.class)。
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Inherited
    @AutoConfigurationPackage
    @Import(AutoConfigurationImportSelector.class)
    public @interface EnableAutoConfiguration {
        String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
        Class[] exclude() default {};
        String[] excludeName() default {};
    }
    
3.5.1 @AutoConfigurationPackage
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(AutoConfigurationPackages.Registrar.class)//给容器中导入一个组件
public @interface AutoConfigurationPackage {
    String[] basePackages() default {};
    Class[] basePackageClasses() default {};
}

该注解直译为:自动配置包,指定了默认的包规则,利用 Registrar 将组件注册到 Ioc 容器中。

3.5.2 @Import(AutoConfigurationImportSelector.class)

AutoConfigurationImportSelector:自动配置导入选择器,将需要的自动配置类注册到 Ioc 容器中。

当工程启动时,默认会加载全部 127 个场景的所有自动配置类,但由于自动配置类上有条件注解@Conditional,只有满足条件的自动配置类才会生效,才能被注册到 Ioc 容器中。

如AopAutoConfiguration类:

@Configuration(
    proxyBeanMethods = false
)
@ConditionalOnProperty(
    prefix = "spring.aop",
    name = "auto",
    havingValue = "true",
    matchIfMissing = true
)
public class AopAutoConfiguration {
	...
}
4、自动配置的流程
  • 工程启动时,SpringBoot 会自动加载所有的自动配置类 xxxAutoConfiguration;
  • 每个自动配置类按照条件进行生效,默认都会绑定配置文件中指定的值(每个自动配置类里都会导入对应的 xxxProperties 类,该类与配置文件进行了绑定,可以从配置文件中获取所需值);
  • 生效的自动配置类向容器中注册相应的组件。
  • 定制化配置:
    ① 通过 @Bean 直接替换默认组件;
    ② 通过 xxxProperties 类查看该组件在配置文件中的 key,修改即可。
5、简化开发 5.1 Lombok
  • 作用:简化 bean 类的代码。
  • 举例:@Data 注解,自动生成当前类所有属性的get、set、toString、equals、hashCode方法。
    @Data
    public class User {
        private Integer uid;
        private String uname;
    }
    
  • 引入:IDEA 2020 版本及以后,默认集成了 Lombok 插件,只需引入其依赖即可。
    
        org.projectlombok
        lombok
    
    
6、Spring Initializr

Spring Initializr 是创建 SpringBoot 工程的向导。
创建步骤:在 IDEA 中,菜单栏New -> Project -> Spring Initializr。

7、配置文件 - yaml

application.yaml 可以替代 application.proterties,作为工程的配置文件。

7.1 语法
  • key: value (冒号和value之间有空格)
  • 大小写敏感
  • 使用缩进表示层级关系
  • 缩进不允许使用 tab,只允许空格
  • 缩进的空格数不重要,只要相同层级的元素左对齐即可
  • ‘#’ 表示注释
  • 字符串无需加引号,如果要加,单引号’’、双引号""表示字符串内容会 转义、不转义
7.2 数据类型
  • 字面量:单个的、不可再分的值。date、boolean、string、number、null
    age: 18
    
  • 对象:键值对的集合。map、hash、set、object
    # 行内写法
    k: {k1:v1,k2:v2,k3:v3}
    
    # 或
    k:
     k1: v1
     k2: v2
     k3: v3
    
  • 数组:一组按次序排列的值。array、list、queue
    # 行内写法:  
    k: [v1,v2,v3]
    
    # 或
    k:
     - v1
     - v2
     - v3
    
8、自定义类绑定的配置提示

当我们在配置文件中设置自定义类的属性值时,一般都没有提示。若需要提示,则在 pom.xml 中引入如下依赖:


    org.springframework.boot
    spring-boot-configuration-processor
    true




    
        
            org.springframework.boot
            spring-boot-maven-plugin
            
                
                    
                        org.springframework.boot
                        spring-boot-configuration-processor
                    
                
            
        
    

9、Web 场景 9.1 静态资源规则与定制化
  • 静态资源的默认存放目录:
    classpath:/META-INF/resources/
    classpath:/resources/
    classpath:/static/
    classpath:/public/
    

    classpath:映射为 maven 工程下的 /resources/ 目录。

  • 静态资源的默认访问路径:localhost:port/静态资源名,会自动到默认存放目录寻找静态资源,因为内部的映射规则为 { @Bean public WebMvcConfigurer webMvcConfigurer(){ return new WebMvcConfigurer() { @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { //用于存放请求参数与媒体类型的映射关系 Map mediaTypes = new HashMap<>(); mediaTypes.put("json",MediaType.APPLICATION_JSON); mediaTypes.put("xml",MediaType.APPLICATION_XML); //自定义媒体类型 mediaTypes.put("gg",MediaType.parseMediaType("application/x-guigu")); //创建基于请求参数的内容协商策略 ParameterContentNegotiationStrategy parameterStrategy = new ParameterContentNegotiationStrategy(mediaTypes); //还需添加请求头处理策略,否则基于请求头的内容协商策略会失效 HeaderContentNegotiationStrategy headeStrategy = new HeaderContentNegotiationStrategy(); configurer.strategies(Arrays.asList(parameterStrategy, headeStrategy)); } } } }

    在浏览器输入http://localhost:8080/test/person?format=gg,返回值处理器会先选择内容协商策略(由于请求地址中包含format请求参数,会选用基于请求参数的内容协商策略),该策略通过解析format=gg判断客户端要接收的媒体类型是application/x-guigu,然后找到匹配的消息转换器将返回值写出(即 GuiguMessageConverter)。

    注意:当我们自定义组件时,可能会覆盖很多默认的功能,导致一些默认功能失效。

    三、Thymeleaf

    Thymeleaf 是适用于 web 和 独立环境 的现代服务器端Java模板引擎。Thymeleaf 官网

    Thymeleaf 的优点:

    • 动静分离: Thymeleaf 选用 html 作为模板页,使用html通过一些特定标签语法代表其含义,但并未破坏html结构,即使无网络、不通过后端渲染也能在浏览器成功打开,大大方便界面的测试和修改。
    • 开箱即用: Thymeleaf 提供标准和Spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、改JSTL、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
    • Springboot官方支持:Springboot官方对 Thymeleaf 做了很多默认配置,开发者只需编写对应html即可,大大减轻了上手难度和配置复杂度。
    1、基本语法 1.1 表达式
    表达式名字语法用途
    变量取值${…}获取请求域、session域、对象等值
    选择变量*{…}获取上下文对象值
    消息#{…}获取国际化等值
    链接@{…}生成链接
    片段表达式~{…}jsp:include 作用,引入公共页面片段
    1.2 字面量
    类型示例
    文本值‘one text’ , ‘Another one!’ ,…
    数字0, 5, 2.3, …
    布尔值true, false
    空值null
    变量one,two,… (变量不能有空格)
    1.3 文本操作
    • 字符串拼接:+
    • 变量替换:|The name is ${name}|
    1.4 数学运算
    • 运算符:+,-,*,/,%
    1.5 布尔运算
    • 运算符:and,or
    • 一元运算:!,not
    1.6 比较运算
    • 比较: >,>=,<,<= (gt,lt,ge,le)
    • 等式:==,!= (eq,ne)
    1.7 条件运算
    • If-then:(if) ? (then)
    • If-then-else:(if) ? (then) : (else)
    • Default:(value) ?: (defaultvalue)
    1.8 设置属性值
    • 设置单个值
    • 设置多个值
      
      
    1.9 遍历
    
        Onions
        2.41
        yes
    
    
    1.9 条件运算
    • th:if
      view
      
    • th:switch

      User is an administrator

      User is a manager

      User is some other thing

    1.10 属性优先级
    OrderFeatureAttributes
    1Fragment inclusionth:insert、th:replace
    2Fragment iterationth:each
    3Conditional evaluationth:if、th:unless、th:switch、th:case
    4Local variable definitionth:object、th:with
    5General attribute modificationth:attr、th:attrprepend、th:attrappend
    6Specific attribute modificationth:value、th:href、th:src、...
    7Text (tag body modification)th:text、th:utext
    8Fragment specificationth:fragment
    9Fragment removalth:remove
    2、进阶使用 2.1 Thymeleaf 内联写法

    Hello, [[${session.user.name}]]!

    上述写法可动态修改标签的文本内容。

    2.2 页面引用
    引用方式效果
    th:include替换当前标签内的所有内容
    th:insert插入当前标签
    th:replace替换当前标签

    假设有公共页面 common.html:

    假设当前标签内有许多内容

    在 test.html 中引用:

    通过片段名进行引用
    通过id进行引用
    四、再探源码 1、视图解析

    视图解析流程(DispatcherServlet):

    • 在HandlerAdapter执行完handle()方法后,会返回一个ModelAndView对象;
    • 接下来调用processDispatchResult()方法处理派发结果:该方法内部调用render(mv, request, response)方法进行页面渲染;
      1. 通过ModelAndView对象获取视图名称;
      2. 遍历所有的ViewResolver视图解析器,找到可以解析当前视图名称的视图解析器,并将其解析为View对象;
      3. view.render(mv.getModelInternal(), request, response),视图对象调用自己的render()方法进行最终的页面渲染。
    2、拦截器 2.1 拦截器添加步骤
    • 编写一个类实现HandlerInterceptor接口
      public class LoginInterceptor implements HandlerInterceptor {
      
      	//目标方法执行之前
          @Override
          public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      
              //登录检查逻辑:登录了直接放行,未登录跳转到登录页面
              HttpSession session = request.getSession();
              Object loginUser = session.getAttribute("loginUser");
              if(loginUser != null){
                  return true;
              }
              request.getRequestDispatcher("/").forward(request,response);
              return false;
          }
      
      	//目标方法执行之后
          @Override
          public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
              log.info("postHandle执行{}",modelAndView);
          }
      
      	//页面渲染之后
          @Override
          public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
              log.info("afterCompletion执行异常{}",ex);
          }
      }
      
    • 把自定义拦截器注册到 Ioc 容器中
      @Configuration
      public class WebConfig implements WebMvcConfigurer{
          @Override
          public void addInterceptors(InterceptorRegistry registry) {
          
              registry.addInterceptor(new LoginInterceptor())
                      .addPathPatterns("
          @ConfigurationProperties("spring.datasource")
          @Bean
          public DataSource dataSource() throws SQLException {
              DruidDataSource druidDataSource = new DruidDataSource();
              //开启监控页和防火墙功能
              druidDataSource.setFilters("stat,wall");
              return druidDataSource;
          }
      
          
          @Bean
          public ServletRegistrationBean statViewServlet(){
              StatViewServlet statViewServlet = new StatViewServlet();
              ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean<>(statViewServlet,"/druid
          @Bean
          public FilterRegistrationBean webStatFilter(){
              WebStatFilter webStatFilter = new WebStatFilter();
              FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean<>(webStatFilter);
              //设置拦截路径
              filterRegistrationBean.setUrlPatterns(Arrays.asList("*.xml,类路径下 /mapper 目录及其子目录下的所有 .xml 文件。
    9.1 基本使用
    • 引入 MyBatis Plus 的官方 starter:
      
          com.baomidou
          mybatis-plus-boot-starter
          3.5.1
      
      
    • 编写 Mapper 接口,并继承BaseMapper类:
      public interface UserMapper2 extends BaseMapper {
      }
      

      怎样确定 User 类对应数据库中的哪张表?
      ① 默认寻找类名首字母小写对应的表,即 user 表;
      ② 手动指明:在 User 类上面标注@TableName("user")注解;

    • 测试 Mapper 的 CURD 功能:
      @SpringBootTest
      class SpringbootAdminApplicationTests {
      
          @Autowired
          UserMapper2 userMapper;
          
          @Test
          void testUserMapper2(){
              User user = userMapper.selectById(1);
              System.out.println(user);
          }
      }
      
    9.2 高级使用 9.2.1 简化 service 层开发
    • 创建 Service 接口,并继承IService接口:
      public interface UserService2 extends IService {
      }
      
    • 创建 Service 接口实现类,并继承ServiceImpl类:
      @Service
      public class UserService2Impl extends ServiceImpl implements UserService2 {
      }
      
    • 测试 Service 的 CURD 功能:
      @SpringBootTest
      class SpringbootAdminApplicationTests {
      
          @Autowired
      	UserService2 userService;
          
          @Test
          void testUserService2(){
              User user = userService.getById(1);
              System.out.println(user);
          }
      }
      
    9.2.2 简化分页
    • 配置分页插件:
      @Configuration
      public class MyBatisPlusConfig {
      
          @Bean
          public MybatisPlusInterceptor mybatisPlusInterceptor(){
              //分页拦截器
              PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
              
              // mybatisPlus 拦截器
              MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
              mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor);
      
              return mybatisPlusInterceptor;
          }
      }
      
    • 测试分页功能:
      @SpringBootTest
      class SpringbootAdminApplicationTests {
      
          @Autowired
         	UserService2 userService;
          
          @Test
          void testPage(){
              Page page = new Page<>(1, 2); //获取第1页,每页2条记录
              Page userPage = userService.page(page);
              System.out.println("当前页数:" + userPage.getCurrent());
              System.out.println("每页显示条数:" + userPage.getSize());
              System.out.println("总页数:" + userPage.getPages());
              System.out.println("总记录数:" + userPage.getTotal());
              System.out.println("当前页数据:" + userPage.getRecords());
          }
      }
      
    10、整合 Redis

    ubuntu 18.04 下 安装 redis
    Redis 学习笔记

    1. 引入 Redis 的 starter:
      
          org.springframework.boot
          spring-boot-starter-data-redis
      
      
    2. 分析自动配置:
      ① 自动配置了 Redis 连接工厂:LettuceConnectionConfiguration、JedisConnectionConfiguration
      ③ SpringBoot 默认引入的是 Lettuce 客户端,所以JedisConnectionConfiguration不生效;
      ④ 自动配置了StringRedisTemplate、RedisTemplate;
    3. 配置 Redis 相关属性
      spring:
      
        redis:
          host: ip
          port: 6379
          password: username:password
      
    4. 测试:
      @SpringBootTest
      class SpringbootAdminApplicationTests {
      
          @Autowired
          RedisTemplate redisTemplate;
      
          @Test
          void testRedis(){
              ValueOperations ops = redisTemplate.opsForValue();
              ops.set("hello","world");
              Object hello = ops.get("hello");
              System.out.println(hello);
          }
      }
      
    11、JUnit 5

    JUnit 5 官方文档

    11.1 简介
    • SpringBoot 2.2.0 版本开始引入 JUnit 5 作为默认的单元测试框架。
      
          org.springframework.boot
          spring-boot-starter-test
          test
      
      
    • JUnit 5 由三个模块组成:JUnit Platform、JUnit Jupiter、JUnit Vintage。

      JUnit Platform: Junit Platform是在 JVM 上启动测试框架的基础,不仅支持 Junit 自制的测试引擎,其他测试引擎也都可以接入。
      JUnit Jupiter: JUnit Jupiter提供了 JUnit 5 的新的编程模型,是JUnit5新特性的核心。内部包含了一个测试引擎,用于在Junit Platform上运行。
      JUnit Vintage: 由于JUint 已经发展多年,为了照顾老的项目,JUnit Vintage 提供了兼容 JUnit4.x,JUnit3.x 的测试引擎。

    • SpringBoot 2.4 以上版本移除了默认对 Vintage 的依赖,如果需要兼容JUnit4 需要自行引入。
    • JUnit 5 已经将 Vintage 从spring-boot-starter-test 中移除。如果需要继续兼容 JUnit4 需要自行引入Vintage 依赖。
      
          org.junit.vintage
          junit-vintage-engine
          test
          
              
                  org.hamcrest
                  hamcrest-core
              
          
      
      
    11.2 常用测试注解
    • @Test:表示当前方法是测试方法。
    • @DisplayName:为测试类或测试方法设置展示名称。
      @DisplayName("JUnit5 测试类")
      @SpringBootTest
      public class JUnit5Test {
      
          @DisplayName("JUnit5 测试方法")
          @Test
          void testDisplayName(){
              System.out.println("测试 @DisplayName 注解");
          }
      }
      
    • @ParameterizedTest:表示当前方法是参数化测试。
      @DisplayName("JUnit5 测试类")
      @SpringBootTest
      public class JUnit5Test {
      
          @ParameterizedTest
          @ValueSource(ints = {1,2,3})
          void testParameterizedTest(int i){
              System.out.println("测试 @ParameterizedTest 注解" + i);
          }
      }
      
    • @RepeatedTest:表示当前方法可重复执行。
      @DisplayName("JUnit5 测试类")
      @SpringBootTest
      public class JUnit5Test {
      
          @RepeatedTest(3)
          void testRepeatedTest(){
              System.out.println("测试 @RepeatedTest 注解");
          }
      }
      
    • @BeforeEach:表示在每个测试方法之前执行。
    • @AfterEach:表示在每个测试方法之后执行。
    • @BeforeAll:表示在所有测试方法之前执行,该注解标注的方法必须是 static 的。
    • @AfterAll:表示在所有测试方法之后执行,该注解标注的方法必须是 static 的。
    • @Tag:表示单元测试类别,类似于JUnit4中的@Categories。
    • @Disabled:表示当前测试类或当前测试方法不执行,类似于JUnit4中的@Ignore。
    • @Timeout:如果当前测试方法运行超时了指定时间,将会返回错误。
      @DisplayName("JUnit5 测试类")
      @SpringBootTest
      public class JUnit5Test {
      
          @Timeout(value = 500, unit = TimeUnit.MILLISECONDS)
          @Test
          void testTimeout() throws InterruptedException {
              System.out.println("测试 @Timeout 注解");
              Thread.sleep(600);
          }
      }
      
    • @ExtendWith:为测试类或测试方法提供扩展类引用。
    11.3 断言机制

    断言(Assertion)是测试方法中的核心部分,用来对测试需要满足的条件进行验证。这些断言方法都是 org.junit.jupiter.api.Assertions 的静态方法。检查业务逻辑返回的数据是否合理。所有的测试运行结束以后,会有一个详细的测试报告。

    11.3.1 简单断言
    方法说明
    assertEquals()判断两个对象或两个原始类型是否相等
    assertNotEquals()判断两个对象或两个原始类型是否不相等
    assertSame()判断两个对象引用是否指向同一个对象
    assertNotSame()判断两个对象引用是否指向不同的对象
    assertTrue()判断给定的布尔值是否为 true
    assertFalse()判断给定的布尔值是否为 false
    assertNull()判断给定的对象引用是否为 null
    assertNotNull()判断给定的对象引用是否不为 null
    @DisplayName("JUnit5 测试类")
    @SpringBootTest
    public class JUnit5Test {
    
        @Test
        void testSimpleAssert(){
            Assertions.assertEquals(1,2,"1不等于2");
    
            Assertions.assertSame(new Object(), new Object(), "你这是两个对象");
    
            Assertions.assertTrue(1 > 2, "1不大于2");
    
            Assertions.assertNull(new Object(), "不为 null");
        }
    }
    

    当某个断言失败后,则该断言下面的代码就不再执行。

    11.3.2 数组断言

    assertArrayEquals():判断两个数组对应位置处的元素是否相等。

    @DisplayName("JUnit5 测试类")
    @SpringBootTest
    public class JUnit5Test {
    
        @Test
        void testArrayAssert(){
            Assertions.assertArrayEquals(new int[]{1,2}, new int[]{2,1});
        }
    }
    
    11.3.3 组合断言

    assertAll():该方法接受多个 org.junit.jupiter.api.Executable 函数式接口的实例作为要验证的断言,可以通过 lambda 表达式很容易的提供这些断言。

    @DisplayName("JUnit5 测试类")
    @SpringBootTest
    public class JUnit5Test {
    
        @Test
        void testAssertAll(){
            Assertions.assertAll(
                    () -> Assertions.assertEquals(2, 2),
                    () -> Assertions.assertTrue(1 > 0)
            );
        }
    }
    

    当组合断言中的某个断言失败时,该断言下面的代码不再执行。

    11.3.4 异常断言

    assertThrows():断言是否会抛出指定异常,配合函数式编程使用。

    @DisplayName("JUnit5 测试类")
    @SpringBootTest
    public class JUnit5Test {
    
        @Test
        void testException(){
            //断言会出现数学运算异常,如果不抛出数学运算异常,则断言失败
            ArithmeticException arithmeticException = Assertions.assertThrows(ArithmeticException.class, () -> System.out.println(1 / 0));
            System.out.println(arithmeticException);
        }
    }
    
    11.3.5 超时断言

    assertTimeout():断言程序运行时间不会超过指定超时时间,配好函数式编程使用。

    @DisplayName("JUnit5 测试类")
    @SpringBootTest
    public class JUnit5Test {
    
        @Test
        void testTime(){
            //断言程序运行时间不会超过500毫秒,如果超过500毫秒,则断言失败
            Assertions.assertTimeout(Duration.ofMillis(500), ()->Thread.sleep(600));
        }
    }
    
    11.3.6 快速失败

    fail():使当前断言直接失败。

    @DisplayName("JUnit5 测试类")
    @SpringBootTest
    public class JUnit5Test {
    
        @Test
        void testFail(){
        	System.out.println("测试 fail() 方法");
            Assertions.fail("断言失败");
        }
    }
    
    11.4 前置条件

    Assumption(假设),类似于断言,不同之处在于不满足的断言会使得测试方法失败,而不满足的前置条件只会使得测试方法终止执行。可以把 Assumption 看作是方法的执行前提,不满足该前提,则方法也就不用再执行了。

    @DisplayName("JUnit5 测试类")
    @SpringBootTest
    public class JUnit5Test {
    
        @Test
        void testAssumption(){
            Assumptions.assumeTrue(1 == 1);
            Assumptions.assumeFalse(1 > 2);
            Assumptions.assumingThat(1 == 1, ()-> System.out.println(666));
        }
    }
    

    assumingThat():第1个参数是布尔型,第2个参数是 Executable 接口的实现对象。当第1个参数为 true 时,后面的 Executable 对象才会执行。

    11.5 嵌套测试

    JUnit 5 可以通过 Java 中的内部类和 @Nested 注解实现嵌套测试。

    • 示例1:
    @DisplayName("JUnit5 测试类")
    @SpringBootTest
    public class JUnit5Test {
    
        List list;
    
        @BeforeEach
        void createNewList(){
            list = new ArrayList<>();
        }
    
        @Nested
        class NestedTest{
        
            @Test
            void isNull(){
                Assertions.assertNull(list);
            }
        }
    }
    

    运行 isNull() 方法,断言失败。表示内部类的测试方法可以驱动外部类的 @BeforeEach、@AfterEach、@BeforeAll、@AfterAll 注解标注的方法。

    • 示例2:
    @DisplayName("JUnit5 测试类")
    @SpringBootTest
    public class JUnit5Test {
    
        List list;
    
        @Test
        void isNull(){
            Assertions.assertNull(list);
        }
    
        @Nested
        class NestedTest{
        
        	@BeforeEach
    	    void createNewList(){
    	        list = new ArrayList<>();
    	    }
        }
    }
    

    运行 isNull() 方法,断言成功。表示外部类的测试方法不可以驱动内部类的 @BeforeEach、@AfterEach 注解标注的方法。(jdk 11 以后,内部类不允许定义静态成员)

    11.6 参数化测试

    参数化测试是 JUnit5 很重要的一个新特性,它使得用不同的参数多次运行测试成为了可能,也为我们的单元测试带来许多便利。

    利用 @ValueSource 等注解,指定入参来源,我们将可以使用不同的参数进行多次单元测试,而不需要每新增一个参数就新增一个单元测试,省去了很多冗余代码。

    注解说明
    @ValueSource为参数化测试指定入参来源,支持八大基础类以及String类型,Class类型
    @NullSource表示为参数化测试提供一个null的入参
    @EnumSource表示为参数化测试提供一个枚举入参
    @CsvFileSource表示读取指定CSV文件内容作为参数化测试入参
    @MethodSource表示读取指定静态方法的返回值作为参数化测试入参(注意方法返回的需要是一个流)
    @DisplayName("JUnit5 测试类")
    @SpringBootTest
    public class JUnit5Test {
    
        @MethodSource("test") //指定方法名
        @ParameterizedTest
        void testMethodSource(String s){
            System.out.println(s);
        }
    
        static Stream test(){
            return Stream.of("hello","world");
        }
    }
    
    11.7 迁移指南

    从 JUnit 4 迁移到 JUnit 5 需注意如下事项:

    • 相关注解在org.junit.jupiter.api包中,断言在org.junit.jupiter.api.Assertions类中,假设在org.junit.jupiter.api.Assumptions 类中。
    • @Before -> @BeforeEach;@After -> @AfterEach
    • @BeforeClass -> @BeforeAll;@AfterClass -> @AfterAll
    • @Ignore -> @Disabled
    • @Category -> @Tag
    • @RunWith + @Rule + @ClassRule -> @ExtendWith
    12、指标监控 12.1 简介

    SpringBoot Actuator 官方文档
    SpringBoot Actuator:未来每一个微服务在云上部署以后,我们都需要对其进行监控、追踪、审计、控制等,SpringBoot 就抽取了 Actuator 场景,使得我们每个微服务快速引用即可获得生产级别的应用监控、审计等功能。

    12.2 基本使用
    1. 引入 actuator 的 starter
      
          org.springframework.boot
          spring-boot-starter-actuator
      
      
    2. 访问http://localhost:8080/actuator
    3. 页面结果
    12.3 actuator 详解 12.3.1 常用端点(endpoint)
    ID描述
    health显示应用程序运行状况信息
    metrics显示当前应用程序的“指标”信息
    loggers显示和修改应用程序中日志的配置
    info显示应用程序信息
    auditevents暴露当前应用程序的审核事件信息,需要一个 AuditEventRepository 组件
    beans显示应用程序中所有 Spring Bean 的完整列表
    caches暴露可用的缓存
    conditions显示自动配置的所有条件信息,包括匹配或不匹配的原因
    configprops显示所有 @ConfigurationProperties
    env暴露Spring的属性ConfigurableEnvironment
    flyway显示已应用的所有 Flyway 数据库迁移,需要一个或多个 Flyway 组件
    httptrace显示HTTP跟踪信息(默认情况下,最近100个HTTP请求-响应),需要一个HttpTraceRepository组件
    integrationgraph显示 Spring integrationgraph,需要依赖 spring-integration-core
    liquibase显示已应用的所有 Liquibase 数据库迁移,需要一个或多个 Liquibase 组件
    mappings显示所有 @RequestMapping 路径列表
    scheduledtasks显示应用程序中的计划任务
    sessions允许从 Spring Session 支持的会话存储中检索和删除用户会话,需要使用 Spring Session 的基于 Servlet 的 Web 应用程序
    shutdown使应用程序正常关闭,默认禁用
    startup显示由 ApplicationStartup 收集的启动步骤数据,需要使用 SpringApplication 进行配置BufferingApplicationStartup
    threaddump执行线程转储

    如果是Web应用程序(Spring MVC、Spring WebFlux 或 Jersey),则可以使用以下附加端点:

    ID描述
    heapdump返回hprof堆转储文件
    jolokia通过 HTTP 暴露 JMX bean(需要引入Jolokia,不适用于WebFlux),需要引入依赖 jolokia-core
    logfile返回日志文件的内容(如果已设置 logging.file.name 或 logging.file.path 属性),支持使用 HTTPRange 标头来检索部分日志文件的内容
    prometheus以 Prometheus 服务器可以抓取的格式公开指标,需要依赖 micrometer-registry-prometheus

    端点的开启与禁用:除了 shutdown 之外的所有端点,默认都是开启的。

    • 手动控制某个端点的开启与禁用:
      management:
        endpoint:
          beans:
            enabled: false
      
    • 禁用所有端点,然后手动指定要开启的端点:
      management:
        endpoints:
          enabled-by-default: false
        endpoint:
          beans:
            enabled: true
          health:
            enabled: true
      

    端点暴露:只有暴露的端点,才可以被访问。

    actuator 支持两种暴露方式:HTTP(默认只暴露 health)、JMX(默认暴露所有的 Endpoint)。

    若要修改默认暴露的 Endpoint,请配置以下的包含和排除属性:

    PropertyDefault
    management.endpoints.jmx.exposure.exclude
    management.endpoints.jmx.exposure.include*
    management.endpoints.web.exposure.exclude
    management.endpoints.web.exposure.includehealth、info
    12.3.2 health Endpoint

    可以在配置文件中设置端点显示详细信息:

    management:
        health:
          enabled: true
          show-details: always #总是显示详细信息。可显示每个模块的状态信息
    

    给 health 端点新增自定义的检查信息:

    • 创建自己的HealthIndicator,并且继承AbstractHealthIndicator
    • 类名必须以 “HealthIndicator” 结尾
    @Component
    public class MyComHealthIndicator extends AbstractHealthIndicator {
    
        @Override
        protected void doHealthCheck(Health.Builder builder) throws Exception {
        	...
    		//自定义检查逻辑
    		...
    		
    		//检查完成,定制显示信息
            Map map = new HashMap<>();
            if(1 == 1){ //如果健康
                //builder.up();
                builder.status(Status.UP);
                map.put("count",1);
                map.put("ms",100);
            }else { //如果不健康
                //builder.down();
                builder.status(Status.OUT_OF_SERVICE);
                map.put("err","连接超时");
                map.put("ms",3000);
            }
    
            builder.withDetail("code",100)
                    .withDetails(map);
        }
    }
    
    12.3.3 info Endpoint

    info 端点默认显示为空,自定义 info 端点显示信息:

    • 方法1:通过配置文件

      info:
        appName: boot-admin
        version: 2.0.1
        mavenProjectName: @project.artifactId@  #使用@@可以获取pom文件值、系统环境变量...
        mavenProjectVersion: @project.version@
      
    • 方法2:创建自定义类实现InfoContributor接口

      @Component
      public class MyInfoContributor implements InfoContributor {
      
          @Override
          public void contribute(Info.Builder builder) {
              builder.withDetail("hello","你好")
                     .withDetail(Collections.singletonMap("key", "value"));
          }
      }
      
    12.3.3 metrics Endpoint

    给 metrics 端点新增自定义的指标信息:

    • 通过MeterRegistry注册监控指标:假设监控 hello() 方法的执行次数
      @Service
      public class MyService {
      
          Counter counter;
      
          public MyService(MeterRegistry registry){
              counter = registry.counter("myservice.hello.count");
          }
      
          public double hello(){
              counter.increment();
              double count = counter.count();
              return count;
          }
      }
      
      @Controller
      public class IndexController {
      @ResponseBody
          @GetMapping("/hello")
          public double count(){
              return myService.hello();
          }
      }
      
    12.3.4 新增自定义监控端点
    @Component
    @Endpoint(id = "container") //id 即为端点名
    public class DockerEndpoint {
    
        @ReadOperation //读方法,返回当我们访问 /actuator/container 时的页面信息
        public Map getDockerInfo(){
            return Collections.singletonMap("info","docker started...");
        }
    
        @WriteOperation //写方法,可以通过 JMX 调用
        private void restartDocker(){
            System.out.println("docker restarted....");
        }
    }
    
    12.4 指标监控可视化

    spring-boot-admin 官方文档
    Spring Boot Admin Server:codecentric 发起的一个开源项目,将上面的指标监控进行可视化展示。

    12.4.1 创建 Admin Server
    1. 新建一个 spring-web 工程;
    2. 引入 Admin Server 的 starter:

      记得与自己工程中引入的 actuator 依赖版本对应。

      
          de.codecentric
          spring-boot-admin-starter-server
          2.6.7
      
      
    3. 在主程序类标注@EnableAdminServer注解:
      @EnableAdminServer
      @SpringBootApplication
      public class SpringbootAdminServerApplication {
      
          public static void main(String[] args) {
              SpringApplication.run(SpringbootAdminServerApplication.class, args);
          }
      }
      
    4. 为了防止端口冲突,修改端口号:
      server:
        port: 8081
      
    5. 访问http://localhost:8081,即可看到可视化界面。
    12.4.2 创建 Admin Client
    1. 在我们的工程中引入 Admin Client 的 starter:

      记得与自己工程中引入的 actuator 依赖版本对应。

      
          de.codecentric
          spring-boot-admin-starter-client
          2.3.1
      
      
    2. 在 application.yaml 中进行以下配置:
      spring:
        application:
          name: MyAdminClient # 设置自己的工程名
          
        boot:
          admin:
            client:
              url: http://localhost:8081 # 设置 admin server 的地址
                             
      management:
        endpoints:
          enabled-by-default: true # 设置启用所有端点
          web:
            exposure:
              include: '*' # 设置以 web 模式暴露所有端点
      
    13、Profile 环境切换

    实际开发中,测试环境与生产环境用的配置文件不同,为了方便多环境适配,SpringBoot 简化了 profile 功能。

    13.1 简单使用
    1. 创建测试类:
      public interface Person {
      
         String getName();
         Integer getAge();
      }
      
      @Profile:该注解即可以标注在类上,又可以标注在方法上。
      @Profile("test") //表示当加载 application-test.yaml 时,该类生效
      @Component
      @ConfigurationProperties("person")
      @Data
      public class Worker implements Person {
      
          private String name;
          private Integer age;
      }
      
      @Profile(value = {"prod","default"}) //表示当加载 application-prod.yaml 时,该类生效
      @Component
      @ConfigurationProperties("person")
      @Data
      public class Boss implements Person {
      
          private String name;
          private Integer age;
      }
      
      @Controller
      public class IndexController {
      	@Autowired
      	private Person person;
      	
      	@GetMapping("/person")
      	public String person(){
      	
      	    //激活了prod,则返回Boss;激活了test,则返回Worker
      	    return person.getClass().toString();
      	}
      }
      
    2. 创建不同环境的配置文件:
      ① 测试环境的配置文件 application-test.yaml:
      person:
        name: test-张三
      
      server:
        port: 7000
      
      ② 生成环境的配置文件 application-prod.yaml:
      person:
        name: prod-张三
      
      server:
        port: 8000
      
    3. 在 application.yaml 中指定使用哪个配置文件
      spring:
        profiles:
          active: prod
      
    4. 启动工程,访问http://localhost:8080/person,结果是 “Boss”。
    13.2 配置加载优先级

    配置文件查找路径:

    1. classpath 根路径;
    2. classpath 根路径下的 /config 目录;
    3. jar包所在目录;
    4. jar包所在目录下的 /config 目录;
    5. jar包所在目录下的 /config 目录的直接子目录;(该条仅在 linux 系统生效)

    配置文件加载顺序:

    1. 当前 jar 包内部的 application.properties 和 application.yml;
    2. 当前 jar 包内部的 application-{profile}.properties 和 application-{profile}.yml
    3. 当前 jar 包外部的 application.properties 和 application.yml
    4. 当前 jar 包外部的 application-{profile}.properties 和 application-{profile}.yml
    5. 命令行运行 jar 包时,仍然可以指定参数

    总结:指定环境优先,外部优先,后面的可以覆盖前面的同名配置项。

    14、自定义 starter

    目标:创建HelloService的 starter。

    1. 创建一个普通的 spring 工程:hello-spring-boot-starter-autoconfigure

      pom.xml:
      
      
          4.0.0
      
          
              org.springframework.boot
              spring-boot-starter-parent
              2.7.0
               
          
      
          com.atguigu
          hello-spring-boot-starter-autoconfig
          0.0.1-SNAPSHOT
          hello-spring-boot-starter-autoconfig
          hello-spring-boot-starter-autoconfig
      
          
              11
          
      
          
              
                  org.springframework.boot
                  spring-boot-starter
              
          
      
      
      HelloServiceAutoConfiguration.java:
      @Configuration
      @EnableConfigurationProperties(HelloProperties.class) //开启属性与配置文件的绑定
      public class HelloServiceAutoConfiguration {
      
          @Bean
          @ConditionalOnMissingBean(HelloService.class) //配置当容器中没有 HelloService 组件时,我们再往容器中放该组件
          public HelloService helloService(){
              return new HelloService();
          }
      }
      
      HelloProperties.java:
      @ConfigurationProperties("hello") //与配置文件进行属性绑定,绑定前缀为 hello
      public class HelloProperties {
      
          private String prefix;
          private String suffix;
      
          public String getPrefix() {
              return prefix;
          }
      
          public void setPrefix(String prefix) {
              this.prefix = prefix;
          }
      
          public String getSuffix() {
              return suffix;
          }
      
          public void setSuffix(String suffix) {
              this.suffix = suffix;
          }
      }
      
      HelloService.java:
      public class HelloService {
      
          @Autowired
          private HelloProperties helloProperties;
      
          public String sayHello(String username){
              return helloProperties.getPrefix() + "##" + username + "##" + helloProperties.getSuffix();
          }
      }
      
      spring.factories:在 SpringBoot 中注册我们自己的自动配置类。
      org.springframework.boot.autoconfigure.EnableAutoConfiguration=
      com.atguigu.hello.auto.HelloServiceAutoConfiguration
      

      工程创建完成,使用 maven 插件 install 到本地。

    2. 创建一个普通的 maven 工程:hello-spring-boot-starter

      该工程无需编写任何代码,只需引入hello-spring-boot-starter-autoconfig依赖。
      pom.xml:
      
      
          4.0.0
      
          org.atguigu
          hello-spring-boot-starter
          1.0-SNAPSHOT
      
          
              11
              11
          
      
          
              
                  com.atguigu
                  hello-spring-boot-starter-autoconfig
                  0.0.1-SNAPSHOT
              
          
      
      
      

      工程创建完成,使用 maven 插件 install 到本地。

    3. 创建一个 spring-web 工程用于测试:hello-spring-boot-starter-test

      引入hello-spring-boot-starter的依赖:
      
          org.atguigu
          hello-spring-boot-starter
          1.0-SNAPSHOT
      
      
      application.properties:
      hello.prefix=aaaa
      hello.suffix=bbbb
      
      HelloController.java:
      @RestController
      public class HelloController {
      
          @Autowired
          private HelloService helloService;
      
          @GetMapping("/hello")
          public String hello(){
              return helloService.sayHello("张三");
          }
      }
      
    4. 测试
      访问http://localhost:8080/hello,浏览器返回aaaa##张三##bbbb。
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/932789.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号