【问题标题】:@RefreshScope not working - Spring Boot@RefreshScope 不工作 - Spring Boot
【发布时间】:2017-12-21 14:18:58
【问题描述】:

我遵循这里描述的方法:https://github.com/jeroenbellen/blog-manage-and-reload-spring-properties,唯一的区别是在我的例子中,属性被用于多个类,所以我将它们全部放在一个实用程序类CloudConfig 中,我参考它使用吸气剂的变量。这是类的样子:

@Configuration
@RefreshScope
public class CloudConfig {

    static volatile int count; // 20 sec

    @Value("${config.count}")
    public void setCount(int count) {
        this.count = count;
    }

    public static int getCount() {
        return count;
    }

}

我在其他类中使用变量count,例如CloudConfig.getCount()。我可以在启动时加载属性,但我无法动态更新它们。谁能告诉我做错了什么?如果我没有制作这个配置类,而是完全按照教程描述的方式进行操作,一切正常,但我无法将其适应我的用例。谁能告诉我我错过了什么?

【问题讨论】:

  • 如果其他类是单例并且只在启动时加载这些值,刷新后它们将不会获得新值。
  • 是的,但是 CloudConfig 中的那些会,我将在其他类中使用 getter (CloudConfig.getCount()),这样它们也会获得正确的值。对吗?
  • 如果你只使用 getter 来设置值,它们不会,它们也不应该是静态的,而是常规方法,否则代理创建将失败。

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


【解决方案1】:

尝试改用@ConfigurationProperties。 例如

@ConfigurationProperties(prefix="config")
public class CloudConfig {

    private Integer count;

    public Integer count() {
        return this.count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

}

reference doc from spring cloud 声明:

@RefreshScope 在 @Configuration 类上工作(技术上),但它 可能导致令人惊讶的行为:例如这并不意味着所有 该类中定义的@Bean 本身就是@RefreshScope。 具体来说,任何依赖于这些 bean 的东西都不能依赖它们 在启动刷新时被更新,除非它本身在 @RefreshScope(它将在刷新时重建,它的 重新注入依赖项,此时它们将被重新初始化 来自刷新的@Configuration)。

【讨论】:

  • 但是我们如何在其他 bean 中引用这些?
  • 自动将 ConfigurationProperties 连接到您的服务中。本段末尾有说明docs.spring.io/spring-boot/docs/current/reference/html/…
  • Spring 文档对 ConfigurationProperties 进行了以下说明:- 外部化配置的注释。如果您想绑定和验证一些外部属性(例如,来自 .properties 文件),请将其添加到配置类中的类定义或 Bean 方法中。我可以知道它与RefershScope有什么关系吗??
【解决方案2】:

其他遇到此问题的人,请确保以下几点:

  1. 您的控制器带有 @RefreshScope 注释
  2. Spring boot actuator 已添加到您的依赖项中,因为它是实际提供这些端点的模块:

    org.springframework.boot 弹簧引导启动器执行器

  3. 刷新端点已更新为:

    http://{ip_address}:{port}/actuator/refresh

  4. 默认情况下不启用刷新端点。您必须通过添加以下行在 bootstrap.properties 文件中明确启用它:

    management.endpoints.web.exposure.include=*

我已启用所有端点,而您也可以启用特定端点。

【讨论】:

  • 您的答案在多个方面都是错误的。没有理由用@RefreshScope 注释控制器,并且只有在需要手动刷新时才需要执行器。
  • 在以前的版本中是必需的,在最新版本中可能不再需要。当答案解决问题时仍然没有任何意义。
猜你喜欢
  • 1970-01-01
  • 2021-10-24
  • 2019-06-06
  • 2019-04-25
  • 2016-05-11
  • 2017-03-07
  • 2019-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多