Spring 销毁方法顺序

Spring destroy methods order

假设我们在 Spring 中有以下配置 class:

@Configuration
public class MyConfiguration {
    @Bean(destroyMethod = "beanDestroyMethod")
    public MyBean myBean() {
        MyBean myBean = new MyBean();
        return myBean;
    }
}

以及以下 MyBean class:

public class MyBean implements DisposableBean {
    @PreDestroy
    public void preDestroyMethod() {
        System.out.println("preDestroyMethod");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("disposableBeanMethod");
    }

    public void beanDestroyMethod() {
        System.out.println("beanDestroyMethod");
    }
}

是否保证方法preDestroyMethoddestroybeanDestroyMethod总是在垃圾收集器销毁 bean 时的顺序相同?

如果上一个问题的答案是"yes",那么这3个方法的执行顺序是什么?

最后我用AbstractApplicationContext的registerShutdownHook()方法解决了我的问题

我有以下@Configuration class:

@Configuration
public class AppConfig {
  @Bean(name = "employee1", 
      initMethod = "beanInitMethod", destroyMethod = "beanDestroyMethod")
  public Employee employee1() {
    ...
  }

  @Bean(name = "employee2", 
      initMethod = "beanInitMethod", destroyMethod = "beanDestroyMethod")
  public Employee employee2() {
    ...
  }
}

以及以下 bean class:

public class Employee implements InitializingBean, DisposableBean {
  @PostConstruct
  public void postConstructMethod() {
    System.out.println("1.1 - postConstructMethod");
  }

  @Override
  public void afterPropertiesSet() throws Exception {
    System.out.println("1.2 - initializingBeanMethod");
  }

  public void beanInitMethod() {
    System.out.println("1.3 - beanInitMethod");
  }

  @PreDestroy
  public void preDestroyMethod() {
    System.out.println("2.1 - preDestroyMethod");
  }

  @Override
  public void destroy() throws Exception {
    System.out.println("2.2 - disposableBeanMethod");
  }

  public void beanDestroyMethod() {
    System.out.println("2.3 - beanDestroyMethod");
  }
}

以及以下主要class:

public class AppMain {
  public static void main(String[] args) {
    AbstractApplicationContext abstractApplicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
    abstractApplicationContext.registerShutdownHook();
  }
}

输出如下:

1.1 - postConstructMethod
1.2 - initializingBeanMethod
1.3 - beanInitMethod
1.1 - postConstructMethod
1.2 - initializingBeanMethod
1.3 - beanInitMethod
...
2.1 - preDestroyMethod
2.2 - disposableBeanMethod
2.3 - beanDestroyMethod
2.1 - preDestroyMethod
2.2 - disposableBeanMethod
2.3 - beanDestroyMethod