簡體   English   中英

以編程方式更改Spring Boot屬性

[英]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());
    }
}

您可以這樣做(我假設您錯誤地省略了示例頂部的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的刷新作用域功能(已經針對這種行為進行了廣泛的測試)。

我很確定您也可以從現有的刷新范圍測試中獲得此信息。

應用程序中使用的屬性必須是用@Value注釋的變量。 這些變量必須屬於Spring管理的類,就像帶有@Component批注的類一樣。

如果要更改屬性文件的值,則可以設置不同的配置文件,並為每個配置文件提供各種.properties文件。

我們應該注意,這些文件是靜態的,並且只能加載一次,因此以編程方式更改它們超出了預期的使用范圍。 但是,您可以在Spring Boot應用程序中設置一個簡單的REST端點,該端點會修改主機文件系統上的文件(很可能在您正在部署的jar文件中),然后在原始Spring Boot應用程序上調用Refresh。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM