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

这里 我们还是先在application.yml中去写一个 test属性 下面加个prop
java springboot在当前测试类中添加临时属性 不影响application和其他范围-LMLPHP

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

直接用 Value 读取属性 然后 在函数中输出就好了
java springboot在当前测试类中添加临时属性 不影响application和其他范围-LMLPHP
然后 我们右键测试方法 选择运行
java springboot在当前测试类中添加临时属性 不影响application和其他范围-LMLPHP
这样 我们的值就被读取到了
java springboot在当前测试类中添加临时属性 不影响application和其他范围-LMLPHP
然后 我们在配置文件中 将这个内容去掉
java springboot在当前测试类中添加临时属性 不影响application和其他范围-LMLPHP
这里 我们直接在测试类中 用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);
    }

}

java springboot在当前测试类中添加临时属性 不影响application和其他范围-LMLPHP
然后 我们右键运行 这里 也是被正确输出了
java springboot在当前测试类中添加临时属性 不影响application和其他范围-LMLPHP
然后 如果 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);
    }

}

args 注意 属性名 前面要加 –
运行之后 输出正常
java springboot在当前测试类中添加临时属性 不影响application和其他范围-LMLPHP
然后 这时 大家都会想花活了 args 和 properties同时设置了 谁的优先级高?
args优先级高啊 直接回答了

11-16 20:05