java - 在什么情况下 Spring 调用 Lifecycle 的启动/停止 Hook ?

标签 java spring configuration lifecycle applicationcontext

我正在尝试理解 Lifecycle 接口(interface)逻辑。 Lifecycle 的文档说:

Containers will propagate start/stop signals to all components that apply within each container, e.g. for a stop/restart scenario at runtime.

但似乎 cantainer 根本没有调用这个方法(开始/停止)。

例如,下一个代码片段的结果只是单个输出“>> call: is running: false”

@Configuration
public class TestApp implements Lifecycle {

    boolean runStatus = false;

    @Override
    public void start() {
        System.err.println(">> call: start (Lifecycle)");
        runStatus = true;
    }

    @Override
    public void stop() {
        System.err.println(">> call: stop (Lifecycle)");
        runStatus = false;
    }

    @Override
    public boolean isRunning() {
        System.err.println(">> call: is running: " + runStatus);
        return runStatus;
    }

    public static void main(String[] args) {
        AbstractApplicationContext ctx = new AnnotationConfigApplicationContext(TestApp.class);
        ctx.stop();
    }
}

附言我听说过 SmartLifecycle,它运行良好。但我对如何正确使用 Lifecycle 中的启动/停止方法很感兴趣。

最佳答案

您应该手动 start()stop() 上下文。

@Configuration
 public class TestApp implements Lifecycle {

  boolean runStatus = false;

  public TestApp (){}


  @Bean
  public TestApp testApp(){
    return new TestApp();
  }

  @Override
  public void start() {
    System.err.println(">> call: start (Lifecycle)");
    runStatus = true;
  }

  @Override
  public void stop() {
    System.err.println(">> call: stop (Lifecycle)");
    runStatus = false;
  }

  @Override
  public boolean isRunning() {
    System.err.println(">> call: is running: " + runStatus);
    return runStatus;
  }

  public static void main(String[] args) {
    AbstractApplicationContext ctx = new AnnotationConfigApplicationContext(TestApp.class);
    ctx.start();
    TestApp ta = ctx.getBean(TestApp.class);
    ctx.stop();
  }
}

关于java - 在什么情况下 Spring 调用 Lifecycle 的启动/停止 Hook ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38031006/

相关文章:

postgresql - 将 PostgreSQL 配置为仅适用于 LOCALHOST 或指定的 ip + 端口

php - 登录 phpMyAdmin 时出现错误 2002

java - 在java中的整个类(class)中运行总计?

spring - 将查询参数映射到 @ModelAttribute 不尊重 @JsonProperty 名称

java - 试图制作一个模仿进程表的程序

java - 确保在 Spring Boot 中 Web 服务器公开 HTTP 之前执行代码

java - “发布到 localhost 的 Tomcatv8.0 服务器”失败并出现多个错误

Java EE Web应用程序和环境配置

java - 如何在eclipse中的 Debug模式下将变量设置为null

java - 访问资源时出现 ClassNotFoundException