我试图了解Lifecycle接口的逻辑。Lifecycle的文档说:

容器将开始/停止信号传播到所有
适用于每个容器,例如在以下位置停止/重启
运行。

但似乎cantainer根本不调用此方法(开始/停止)。

例如,下一个代码段的结果仅为单个输出“>> call:正在运行: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方法很感兴趣。

最佳答案

您应该手动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/

10-13 08:03