热部署&宽松/松散绑定配置&测试

热部署

启动热部署

  • 开启开发者工具

    激活方式:ldea失去焦点5秒后启动热部署
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
    
  • 使用构建操作启动热部署:

    快捷键:ctr1 + F9

    idea:build->build Project

  • 关于热部署

    热部署仅仅加载当前开发者自定义开发的资源,不加载jar资源
    
    重启(Restart):自定义开发代码,包含类、页面、配置文件等,加载位置restart类加载器
    重载(ReLoad):jar包,加载位置base类加载器
    

自动启动热部署

  • 设置自动构建项目

    idea:在setting里的Build,Execution,Deployment->Compiler勾选Build project automatically选项,快捷键ctrl+shift+alt+/选择registery勾选compiler.automake.allow.when.app.running。

    激活方式: ldea失去焦点5秒后启动热部署

热部署范围配置

  • 默认不触发重启的目录列表

  • /META-INF/maven
    /META-INF/resources
    /resources
    /static
    /public
    /templates
    
  1. 自定义不参与重启排除项

    devtools:
     restart:
     #设置不参与热部署的文件或文件夹
      exclude: public/**,static/**
      #禁用热部署
      enabled: false
    

禁用热部署

  • 设置高优先级属性禁用热部署(优先级可参考之前文章中的文档优先级判定)

    public static void main(String[] args){
        System.setProperty("spring.devtools.restart.enabled""false");
        SpringApplication.run(MyApplication.class);
    }
    

配置高级

@ConfigurationProperties宽松绑定/松散绑定

  • 使用@ConfigurationProperties为第三方bean绑定属性

    @Bean
    @ConfigurationProperties(prefix = "datasource")
    public DruidDataSource dataSource(){
        DruidDataSourse ds = new DruidDataSource();
        return ds;
    }
    
    
    datasource:
     driverClassName: com.mysql.jdbc.Driver
    
  • @EnableConfigurationProperties注解可以将使用@ConfigurationProperties注解对应的类加入spring容器

    @SpringBootApplication
    @EnableConfigurationProperties(ServerConfig.class)
    public class DemoApplication{
        ...
    }
    
    //@Component
    @Data
    @ConfigurationProperties
    public class ServerConfig{
        
    }
    

    注意事项

    @EnableConfigurationProperties与@Component不能同时使用
    
  • 解除使用 @ConfigurationProperties注解警告

    提示:Spring Boot Configuration Annotation Processor not configured Open Documentation...
    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
    </dependency>
    

宽松/松散绑定

  • @ConfigurationProperties绑定属性支持属性名宽松绑定

    public class ServerConfig{
        private String ipAddress;
        private int port;
        private long timeout;
    }
    
    • 支持的模式有:
      • 驼峰模式
      • 下划线模式
      • 中划线模式
      • 常量模式
  • 注意事项

    宽松绑定不支持注解@Value引用单个属性的方式(@Value注解不支持松散绑定)
    绑定前缀名命名规范:仅能使用纯小写字母、数字、下划线作为合法的字符---@ConfigurationProperties(prefix = "datasource")
    

常用计量单位绑定

  • Spring boot支持JDK8提供的时间与空间计量单位

  • JDK支持的时间与空间计量单位

    在这里插入图片描述

数据校验

  • 开启 Bean 数据校验有助于系统安全性,J2EE规范中JSR303规范定义了一组有关数据校验相关的API

    1. 添加JSR303规范坐标与Hibernate校验框架对应坐标
    <!--1.导AJSR303规范-->
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
    </dependency>
    
    <!--使用hibernate框架提供的校验器做实现类-->
    <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
    </dependency>
    
    1. 对Bean开启校验功能(使用@Validated注解启用校验功能)

      @Component
      @Data
      @ConfigurationProperties(prefix ="servers")
      @Validated
      public class ServerConfig {
          
      }
      
    2. 开启之后时并没有做数据效验的,所以要设置校验规则

      @Component
      @Data
      @ConfigurationProperties(prefix ="servers")
      @Validated
      public class ServerConfig {
          @Max(value = 400,message = “最大值不能超过400" )
               privte int port;
      }        
      

测试

测试加载测试专用属性

加载测试临时属性应用于小范围测试环境

  • 在启动测试环境时可以通过properties参数设置测试环境专用的属性

    @SpringBootTest(properties = {"test.prop=testValue1"})
    public class PropertiesAndArgsTest {
        @Value("${test.prop}")
        private String msg;
        
        @Test
        void testProperties(){
            System.out.println(msg);
        }
    }
    
    • 优势:比多环境开发中的测试环境影响范围更小,仅对当前测试类有效
  • 在启动测试环境时可以通过args参数设置测试环境专用的传入参数

    @SpringBootTest(args = {"--test.arg=testValue2"})
    public class PropertiesAndArgsTest {
        @Value("${test.arg}")
        private String msg;
        
        @Test
        void testArgs(){
            System.out.println(msg);
        }
    }
    
    

加载测试专用配置

加载测试范围配置应用于小范围测试环境

  • 使用@Import注解加载当前测试类专用的配置

    @SpringBootTest
    @Import(MsgConfig.class)
    public class ConfigurationTest {
        @Autowired
        private String msg;
        @Test
        void testConfiguration(){
            System.out.println(msg);
        }
    }
    

Web环境模拟测试

web环境模拟测试
    设置测试端口
    模拟测试启动
    模拟测试匹配(各组成部分信息均可匹配 )
  • 模拟端口

    @SpringBootTest(webEnvironment = SpringBootTest,WebEnvironment.RANDOM_PORT)
    public class WebTest{
        @Test
        void testRandomPort () {}
    }
    
    MOCK
    DEFINED_PORT
    RANDOM_PORT
    NONE
    
  • 虚拟请求测试

    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    //开启虚拟MVC调用
    @AutoConfigureMockMvc
    public class WebTest {
        @Test
        //注入虚拟MVC调用对象
        public void testweb(@Autowired MockMvc mvc) throws Exception {
            //创建虚拟请求,当前访问/books
            MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books");
            //执行请求
            ResultActions action = mvc.perform(builder);
        }
    }
    
  • 虚拟请求状态匹配

    @Test
    public void testSataus(@Autowired MockMvc mvc) throws Exception {
        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books");
        ResultActions action = mvc.perform(builder);
        //匹配执行状态(是否预期值)
        //定义执行状态匹配器
        StatusResultMatchers status = MockMvcResultMatchers.status();
        //定义预期执行状态
        ResultMatcher ok = status.isOk();
        //使用本次真实执行结果与预期结果进行比对
        action.andExpect(ok);
    }
    
  • 虚拟请求体匹配

    @Test
    public void testBody(@Autowired MockMvc mvc) throws Exception {
        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books");
        ResultActions action = mvc.perform(builder);
        //匹配执行结果(是否预期值)
        //定义执行结果匹配器
        ContentResultMatchers content = MockMvcResultMatchers.content();
        //定义预期执行结果
        ResultMatcher result = content().string("springboot");
        //使用本次真实执行结果与预期结果进行比对
        action.andExpect(result);
    }
    
  • 虚拟请求体 (json)匹配

    @Test
    public void testJson(@Autowired MockMvc mvc) throws Exception {
        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders,get("/books");
        ResultActions action = mvc.perform(builder);
        //匹配执行结果(是否预期值)
        //定义执行结果匹配器
        ContentResultMatchers content = MockMvcResultMatchers.content();
        //定义预期执行结果
        ResultMatcher result = content,json("[ "id ":1, "name ":\"SpringBoot2\")");
        //使用本次真实执行结果与预期结果进行比对
        action.andExpect(result);
    }
    
  • 虚拟请求头匹配

    @Test
    public void testContentType(@Autowired MockMvc mvc) throws Exception {
        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books");
        ResultActions action = mvc.perform(builder);
        HeaderResultMatchers header = MockMvcResultMatchers.header();
        ResultMatcher resultHeader = header.string("Content-Type", "application/json");
        action.andExpect(resultHeader);
    }
    

数据层测试回滚

  • 为测试用例添加事务**@Transactional**,Spring Boot会对测试用例对应的事务提交操作进行回滚

    @SpringBootTest
    @Transactional
    public class DaoTest {
        @Autowired
        private BookService bookService;
    }
    
  • 如果想在测试用例中提交事务,可以通过**@Rollback**注解设置

    @SpringBootTest
    @Transactional
    @Rollback(false)
    public class DaoTest {
        
    }
    

测试用例数据设定

  • 测试用例数据通常采用随机值进行测试,使用Spring Boot提供的随机数为其赋值

    testcast:
     book: 
      id: ${random.int) #随机整数
      id2: ${random.int(10)} # 10以内随机数
      type: ${random.int(10,20)} # 10到20随机数
      uuid: ${random.uuid} # 随机uuid
      name: ${random.value} # 随机字符串MD5字符串,32位
      publishTime: ${random.long} # 随机整数(Long范围)
    
    • ${random.int}表示随机整数
    • ${random.int(10)}表示10以内的随机数
    • ${random.int(1,20)}表示10到20的随机数
    • 其中()可以是任意字符,例如[],!!均可
  • 22
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值