Aliuk
Aliuk

Reputation: 1359

Spring destroy methods order

Supossing we have the following configuration class in Spring:

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

And the following 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");
    }
}

Is it guaranteed that the methods preDestroyMethod, destroy and beanDestroyMethod always execute in the same order when the bean is destroyed by the garbage collector?

If the answer to the previous question is "yes", what would be the order of execution of the 3 methods?

Upvotes: 1

Views: 1081

Answers (1)

Aliuk
Aliuk

Reputation: 1359

Finally I solved my question by using the registerShutdownHook() method of AbstractApplicationContext.

I have the following @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() {
    ...
  }
}

And the following 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");
  }
}

And the following main class:

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

And the output is the following:

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

Upvotes: 1

Related Questions