SpringCloud 自定義引導程序Property源

2023-06-06 17:09 更新

引導過程添加的外部配置的默認屬性來源是Spring Cloud Config服務(wù)器,但是您可以通過將類型?PropertySourceLocator?的beans添加到引導上下文(通過?spring.factories?)來添加其他來源。例如,您可以從其他服務(wù)器或數(shù)據(jù)庫插入其他屬性。

例如,請考慮以下定制定位器:

@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?是即將創(chuàng)建的?ApplicationContext?的那個,換句話說,就是我們?yōu)槠涮峁┢渌麑傩栽吹哪莻€。它已經(jīng)有其正常的Spring Boot提供的屬性源,因此您可以使用這些屬性來定位特定于此?Environment?的屬性源(例如,通過在?spring.application.name?上鍵入它,這與默認設(shè)置相同)。 Spring Cloud Config服務(wù)器屬性源定位符)。

如果您創(chuàng)建一個包含此類的jar,然后添加包含以下內(nèi)容的?META-INF/spring.factories?,則?customProperty? ?PropertySource?會出現(xiàn)在任何在其類路徑中包含該jar的應(yīng)用程序中:

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


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號