java - 以编程方式更改 Spring Boot 属性

标签 java spring spring-cloud

我正在尝试为使用@RefreshScope的应用程序编写测试。我想添加一个实际更改属性并断言应用程序正确响应的测试。我已经弄清楚如何触发刷新(在 RefreshScope 中 Autowiring 并调用 refresh(...)),但我还没有找到修改属性的方法。如果可能的话,我想直接写入属性源(而不是必须使用文件),但我不确定在哪里查找。

更新

这是我正在寻找的示例:

public class SomeClassWithAProperty {
    @Value{"my.property"}
    private String myProperty;

    public String getMyProperty() { ... }
}

public class SomeOtherBean {
    public SomeOtherBean(SomeClassWithAProperty classWithProp) { ... }

    public String getGreeting() {
        return "Hello " + classWithProp.getMyProperty() + "!";
    }
}

@Configuration
public class ConfigClass {
    @Bean
    @RefreshScope
    SomeClassWithAProperty someClassWithAProperty() { ...}

    @Bean
    SomeOtherBean someOtherBean() {
        return new SomeOtherBean(someClassWithAProperty());
    }
}

public class MyAppIT {
    private static final DEFAULT_MY_PROP_VALUE = "World";

    @Autowired
    public SomeOtherBean otherBean;

    @Autowired
    public RefreshScope refreshScope;

    @Test
    public void testRefresh() {
        assertEquals("Hello World!", otherBean.getGreeting());

        [DO SOMETHING HERE TO CHANGE my.property TO "Mars"]
        refreshScope.refreshAll();

        assertEquals("Hello Mars!", otherBean.getGreeting());
    }
}

最佳答案

您可以这样做(我假设您错误地省略了示例顶部的 JUnit 注释,因此我会为您将它们添加回来):

@SpringBootTest
public class MyAppIT {

    @Autowired
    public ConfigurableEnvironment environment;

    @Autowired
    public SomeOtherBean otherBean;

    @Autowired
    public RefreshScope refreshScope;

    @Test
    public void testRefresh() {
        assertEquals("Hello World!", otherBean.getGreeting());

        EnvironmentTestUtils.addEnvironment(environment, "my.property=Mars");
        refreshScope.refreshAll();

        assertEquals("Hello Mars!", otherBean.getGreeting());
    }
}

您的主类还需要一个 @SpringBootApplication 注释。

但是您并没有真正测试代码,只是测试 Spring Cloud 的刷新范围功能(已经针对此类行为进行了广泛测试)。

我很确定您也可以从刷新范围的现有测试中得到这一点。

关于java - 以编程方式更改 Spring Boot 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35341684/

相关文章:

Spring Boot Feign Client 方法参数过多

java - 如何测量 i7 上的 java 性能?

java - 如何在仍然具有连续循环的情况下避免堆栈溢出?

java - 从文本文件中读取单词和数字

java - 注释 Propagation.NEVER 不起作用

aws-lambda - 将 aws lambda 与 java 和 Spring Cloud Functions 用于其他语言是一个好主意吗?

java - 加载相关主页但不登录该网站

spring - 如何删除 Mongo 中嵌套对象的唯一索引

spring - 如何从多个路径制作 Spring 加载 JPA 类?

spring-boot - 如何使用 Spring Cloud Stream 4.x 生产者和消费者检测 Spring Boot 3.x 以关联记录器中的跟踪信息