在什么情况下 Spring 调用 Lifecycle 的 start/stop 钩子?

In what condition Spring call Lifecycle's start/stop hooks?

我正在尝试了解 Lifecycle 界面逻辑。 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 根本不调用此方法 (start/stop)。

例如,下一个代码片段的结果只是单个输出 ">> call: is 运行: 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();
    }
}

P.S。我听说 SmartLifecycle 并且效果很好。但我对如何正确使用 Lifecycle.

中的 start/stop 方法很感兴趣

您应该手动 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();
  }
}