• java springboot在当前测试类中添加临时属性 不影响application和其他范围


    目前 我们的属性基本都写在 application.yml 里面了
    但是 如果 我们只是想做一下临时变量的测试 有没有办法实现呢?
    显然是有的

    这里 我们还是先在application.yml中去写一个 test属性 下面加个prop
    在这里插入图片描述

    然后 我们尝试在测试类中 获取一下这个属性

    直接用 Value 读取属性 然后 在函数中输出就好了
    在这里插入图片描述
    然后 我们右键测试方法 选择运行
    在这里插入图片描述
    这样 我们的值就被读取到了
    在这里插入图片描述
    然后 我们在配置文件中 将这个内容去掉
    在这里插入图片描述
    这里 我们直接在测试类中 用SpringBootTest声明就好

    package com.example.webdom;
    
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.test.context.SpringBootTest;
    
    @SpringBootTest(properties = {"test.prop=testValue1"})
    public class WebDomApplicationTests {
    
        @Value("${test.prop}")
        private String Data;
    
        @Test
        void contextLoads() {
            System.out.println(Data);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    在这里插入图片描述
    然后 我们右键运行 这里 也是被正确输出了
    在这里插入图片描述
    然后 如果 application 和当前 配置的临时 都设置了同一个 用谁的?
    临时属性优先级高
    例如 都设置了 data 配置文件 1 当前测试类 临时属性 2 则 在当前测试类拿到的是 2

    然后 临时属性 还有一种写法

    我们将测试类代码改成这样

    package com.example.webdom;
    
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.test.context.SpringBootTest;
    
    @SpringBootTest(args = {"--test.prop=testValue2"})
    public class WebDomApplicationTests {
    
        @Value("${test.prop}")
        private String Data;
    
        @Test
        void contextLoads() {
            System.out.println(Data);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    args 注意 属性名 前面要加 –
    运行之后 输出正常
    在这里插入图片描述
    然后 这时 大家都会想花活了 args 和 properties同时设置了 谁的优先级高?
    args优先级高啊 直接回答了

  • 相关阅读:
    Kotlin笔记(三):扩展函数,运算符重载
    一个小台灯
    力扣:343. 整数拆分
    设计模式-14-迭代器模式
    华为机试 - 真正的密码
    python 基础:文件夹的创建
    DJ12-2-2 算术运算指令
    JVM启动参数大全及默认值
    PostgreSQL缓存管理
    微电网两阶段鲁棒优化经济调度方法(完美复现)
  • 原文地址:https://blog.csdn.net/weixin_45966674/article/details/134445820