【问题标题】:Refresh spring.active.profile at runtime using refreshscope - spring boot and cloud在运行时使用 refreshscope 刷新 spring.active.profile - spring boot 和 cloud
【发布时间】:2023-03-25 08:01:01
【问题描述】:

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

application-mocked-ecom.yml

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

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

如果我从 application.yml 中删除 mocked-ecom 并保存它,然后调用刷新后 api 调用 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

【问题讨论】:

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


    【解决方案1】:

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

    application-mocked-ecom.yml

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

    【讨论】:

    • 感谢您的回复。我尝试通过更改属性并出现新值,但如果可能,我要求更改配置文件
    猜你喜欢
    • 2016-08-06
    • 2022-01-09
    • 2018-03-28
    • 2019-01-19
    • 1970-01-01
    • 2019-01-24
    • 2019-06-09
    • 2017-12-21
    • 1970-01-01
    相关资源
    最近更新 更多