使用refreshscope在运行时刷新spring.active.profile - spring boot和cloud

时间:2017-05-05 10:29:51

标签: spring spring-boot spring-cloud spring-cloud-config

Java类:

package com.hm.refreshscoperesearch;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RefreshScope
@RestController
public class RefreshScopeResearchApplication {

    @Value("${integrations.ecom.api-url}")
    private String url;

     @RequestMapping("/hello")
        String hello() {
            return "Hello " + url + "!";
        }

    public static void main(String[] args) {
        SpringApplication.run(RefreshScopeResearchApplication.class, args);
    }
}

application.yml

spring:
  profiles:
    active: default,mocked-ecom

integrations:
  ecom:
    api-url: dev-api.com

management:
  security:
    enabled: false

应用嘲笑-ecom.yml

integrations:
  ecom:
    api-url: mock-api.com

当我点击http://localhost:8080/hello时,我得到回复“Hello mock-api.com!”。

如果我从application.yml中删除mocked-ecom并保存它,然后调用post refresh api call http://localhost:8080/refresh来刷新上下文,我希望结果为“Hello dev-api.com!”但我得到“Hello mock-api.com!”。

如何在spring boot中使用refreshscope在运行时刷新配置文件?

spring:
  profiles:
    active: default

integrations:
  ecom:
    api-url: dev-api.com

management:
  security:
    enabled: false

1 个答案:

答案 0 :(得分:0)

我不确定您是否可以在运行时更改Spring配置文件值。您可以在其中一个活动配置文件中更改属性的值,并且POST / to refresh应该选择新值。尝试更改:

应用嘲笑-ecom.yml

integrations:
  ecom:
    api-url: new-mock-api.com