Spring Cloud自定义引导属性源

引导过程添加的外部配置的默认属性源是Config Server,但您能够经过将PropertySourceLocator类型的bean添加到引导上下文(经过spring.factories)添加其余源。您能够使用此方法从其余服务器或数据库中插入其余属性。java

做为一个例子,请考虑如下微不足道的自定义定位器:spring

@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是要建立的ApplicationContextEnvironment,即为咱们提供额外的属性来源的。它将已经具备正常的Spring Boot提供的资源来源,所以您能够使用它们来定位特定于此Environment的属性源(例如经过将其绑定在spring.application.name上,如在默认状况下所作的那样Config Server属性源定位器)。数据库

若是你在这个类中建立一个jar,而后添加一个META-INF/spring.factories包含:bootstrap

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

那么“customProperty”PropertySource将显示在其类路径中包含该jar的任何应用程序中。服务器

完整项目的源码来源 技术支持1791743380app

相关文章
相关标签/搜索