【问题标题】:Is it possible to load properties from a web service during spring boot application startup?是否可以在 Spring Boot 应用程序启动期间从 Web 服务加载属性?
【发布时间】:2018-08-06 23:00:07
【问题描述】:

我正在构建一个新的 Spring Boot 应用程序,该应用程序可部署到 Bluemix(Cloud Foundry),它需要执行以下操作:

  1. 使用 spring-cloud-cloudfoundry-connector 发现用户提供的“属性服务”:从 VCAP_APPLICATION 环境变量中读取服务 URL 和凭据。 这一步就完成了。

  2. 通过 HTTP 调用连接到属性服务,接收 JSON 响应,解析单个属性值并将它们公开为应用程序属性(在 Environment 对象中?)

在 spring-boot 应用程序中正确的解决方案是什么?

在较旧的非启动 Spring 应用程序中,属性服务调用将在 Spring 生命周期的早期由扩展 PropertySourcesPlaceholderConfigurer 的类启动,并且来自服务的属性集合将在同一类的 postProcessBeanFactory() 方法调用中处理。

public class CustomPopertiesFactory 
    extends PropertySourcesPlaceholderConfigurer
    implements EnvironmentAware {

private Properties properties;

getServiceCredentials() {
   // parse VCAP_APPLICATION json
   final String localVcapServices = System.getProperty("VCAP_SERVICES");
  // extract url, username, pwd to connect to the service
}

connectToService () {
   // via HTTP request using RestTemplate
   // parse JSON response and add properties to this.properties
    ... this.properties.put("prop1", valueFromJson);

}


@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    getServiceCredentials();

    connectToService();

    // load values from properties service into app properties
    setProperties(properties);
    // continue with lifecycle and load properties from other sources
    super.postProcessBeanFactory(beanFactory);
}

}

在云和本地 spring 配置文件 IMO 之间维护和切换是很痛苦的,我想知道 spring boot 是否有更好的方法来处理外部属性。

【问题讨论】:

    标签: spring spring-boot properties external


    【解决方案1】:

    我最终将“属性服务”替换为 spring-cloud-config-server 并使用spring-cloud-config-client
    在我的 Spring Boot 应用程序中使用来自 spring-cloud-config-server 的属性。

    【讨论】:

      猜你喜欢
      • 2018-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-28
      • 2018-06-25
      • 2022-07-08
      • 1970-01-01
      相关资源
      最近更新 更多