【问题标题】:Spring Boot: Capture event on context load time and on property changeSpring Boot:在上下文加载时间和属性更改时捕获事件
【发布时间】:2018-10-12 14:33:45
【问题描述】:

我想在应用程序启动后以及 Spring Cloud 配置存储库/服务器中的属性更改时立即执行自定义逻辑。所以我写了这样的东西:

import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfiguration implements ApplicationListener<EnvironmentChangeEvent> {

    @Override
    public void onApplicationEvent(EnvironmentChangeEvent event) {
        // Custom logic goes here. It should be executed on both app context load time
        // and on any property change time

    }

}

上面的代码在几个月前的应用程序加载时间和属性更改时工作。但是这段代码最近停止工作了,我猜是 Spring boot / 云版本更新。

目前我正在使用 Sprig boot 1.5.10 和 Cloud Edgware.SR3

【问题讨论】:

  • 看起来像 EnvironmentChangedEvent 以前在启动时调用,但现在在较新的版本中它不会在启动时调用。

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


【解决方案1】:

找到了一种方法来运行自定义逻辑以在加载时间和属性更改时间运行它。

基本上更改为上述代码以在任何事件上调用,然后在覆盖的方法中 onApplicationEvent 仅检查以下事件

  1. ContextRefreshedEvent - 应用程序上下文被初始化或刷新时引发的事件。
  2. EnvironmentChangeEvent - 发布事件以表明环境发生变化,例如配置存储库中的属性。

    import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
    import org.springframework.context.ApplicationEvent;
    import org.springframework.context.ApplicationListener;
    import org.springframework.context.event.ContextRefreshedEvent;
    
    public class AppConfiguration implements ApplicationListener<ApplicationEvent> {
    
      @Override
      public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof EnvironmentChangeEvent || event instanceof ContextRefreshedEvent) {
           // Custom logic goes here. It should be executed on both app context load time 
           // and on any property change time
        }
      }
    }
    

更新

我们也可以使用@EventListener注解来做类似的事情,非常简单好用。参考下面的例子:

@Configuration
public class AppConfiguration {

    @EventListener({EnvironmentChangeEvent.class, ContextRefreshedEvent.class})
    public void onRefresh() {
        // Your code goes here...
    }

}

【讨论】:

    猜你喜欢
    • 2017-01-16
    • 1970-01-01
    • 2017-03-17
    • 2012-11-28
    • 2019-03-30
    • 2017-11-17
    • 2018-10-03
    • 2018-07-20
    • 1970-01-01
    相关资源
    最近更新 更多