以编程方式更改 Spring 引导属性

Changing Spring Boot Properties Programmatically

我正在尝试为使用 @RefreshScope 的应用程序编写测试。我想添加一个实际更改属性并断言应用程序正确响应的测试。我已经想出如何触发刷新(在 RefreshScope 中自动装配并调用 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());
    }
}

应用程序中使用的属性必须是用@Value 注释的变量。这些变量必须属于由 Spring 管理的 class,就像在带有 @Component 注释的 class 中一样。

如果要更改属性文件的值,可以设置不同的配置文件,并为每个配置文件设置不同的 .properties 文件。

我们应该注意这些文件是静态的并且加载一次,因此以编程方式更改它们有点超出预期用途的范围。但是,您可以在 spring 启动应用程序中设置一个简单的 REST 端点,该应用程序修改主机文件系统上的文件(很可能在您正在部署的 jar 文件中),然后在原始 spring 启动应用程序。

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

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
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());
    }
}

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

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