Spring Cloud自定義引導屬性源

引導過程添加的外部配置的默認屬性源是Config Server,但您可以通過將PropertySourceLocator類型的bean添加到引導上下文(通過spring.factories)添加其他源。您可以使用此方法從其他服務器或數據庫中插入其他屬性。

作爲一個例子,請考慮以下微不足道的自定義定位器:

@Configuration
public class CustomPropertySourceLocator implements PropertySourceLocator {
    @Override
    public PropertySource<?> locate(Environment environment) {
        return new MapPropertySource("customProperty",
               Collections.<String, Object>singletonMap("property.from.sample.custom.source", "worked as intended"));
    }
}

傳入的Environment是要創建的ApplicationContext的Environment,即爲我們提供額外的屬性來源的。它將已經具有正常的Spring Boot提供的資源來源,因此您可以使用它們來定位特定於此Environment的屬性源(例如通過將其綁定在spring.application.name上,如在默認情況下所做的那樣Config Server屬性源定位器)。

如果你在這個類中創建一個jar,然後添加一個META-INF/spring.factories包含:

org.springframework.cloud.bootstrap.BootstrapConfiguration=sample.custom.CustomPropertySourceLocator

那麼“customProperty”PropertySource將顯示在其類路徑中包含該jar的任何應用程序中。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章