Spring Cloud配置刷新后如何执行自定义逻辑?

X3n*_*3no 4 java spring spring-boot spring-cloud spring-cloud-config

我将我的应用程序设置为使用 Spring 云配置来提供配置,并启用监视器,以便配置服务器将更改事件发布到我的应用程序。配置已正确更新,但我希望在配置更改时收到通知,以便我可以根据新配置执行一些自定义逻辑。

我有这个配置对象

@Configuration
@RefreshScope
@ConfigurationProperties(prefix = "my.prefix")
public class MyConfig {
    private Map<String, MyObject> configs;
    private String someValue;

    public Map<String, MyObject> getConfigs(){...}
    public void setConfigs(){...}

    public String getSomeValue(){...}
    public void setSomeValue(){...}
}
...
public class MyObject {
   private String field1;

   public String getField1() {...}
   public void setField1() {...}
}
Run Code Online (Sandbox Code Playgroud)

这在我的配置服务器 application.yml 中

my:
  prefix:
    configs:
      TEST:
        field1: "testValue"
    someValue: "test"
Run Code Online (Sandbox Code Playgroud)

现在,当我更改配置中的 someValue 并且配置服务器发布刷新时,它会调用 setSomeValue() 并将该值更新为新值。我可以将自定义逻辑添加到 setSomeValue() 中,它会正常工作。然而,在更新或添加/删除配置中的条目时,它似乎没有调用 setConfigs() 或 setField1() 。

我尝试注册 EnviornmentChangeEvents、RefreshEvents 或 RefreshScopeRefreshedEvents 的侦听器,但这些侦听器要么在 Spring 更新值之前触发,要么根本不触发。我还尝试向 @PreDestroy 和 @PostConstruct 方法添加逻辑,但最终仅调用 PreDestroy,并且在更新配置之前调用它。我还尝试实现 InitializingBean 并将我的逻辑放入 afterPropertiesSet() 中,但它也从未被调用。

当此配置更新时,我如何收到通知?

Jor*_*nez 5

使用 RefreshScopeRefreshedEvent Listener,您可以在配置更新时收到通知。

以下示例对我有用:

配置:

@Configuration
public class Config {
    @Bean
    @RefreshScope
    public A aBean() {
        return new A();
    }

    @Bean
    public RefreshScopeRefreshedListener remoteApplicationEventListener(A aBean) {
        return new RefreshScopeRefreshedListener(aBean);
    }

}
Run Code Online (Sandbox Code Playgroud)

还有听者:

public class RefreshScopeRefreshedListener implements ApplicationListener<RefreshScopeRefreshedEvent> {
    private A aBean;

    public RefreshScopeRefreshedListener(A abean) {
        this.aBean = abean;
    }

    @Override
    public void onApplicationEvent(RefreshScopeRefreshedEvent event) {
        System.out.println(aBean.getValue());

    }

}
Run Code Online (Sandbox Code Playgroud)

它总是打印配置的新值。

如果您已经尝试过这个侦听器,您确定它已注册良好吗?bean 是否已正确创建?