Search code examples
javaspringjavabeansdestructor

SpringBoot: Destroy bean after last use / initialization phase


I have a Closeable bean that I only use during initialization of the application, but not later. It opens a resource that is used during initialization. I would like the close method to be called as early as possible after the last use of the object. Is it possible to auto-destroy objects.

Example

@Component
@Slf4j
public class InitHelper implements Closeable {
  public InitHelper() {
    log.debug("Initialized InitHelper");
  }
  public int hello() {
    return 42;
  }
  @PreDestroy
  public void close() {
    log.debug("Closed InitHelper");
  }
}
@Configuration
public class AppConfig {
  @Bean
  public A a(InitHelper initHelper) {
    return new A(initHelper.hello());
  }

  @Bean
  public B b(InitHelper initHelper) {
    return new A(initHelper.hello());
  }
}

Expected behavior

A InitHelper bean gets initialized before A and B and destroyed after a and b were completed.

Actual behavior

The InitHelper.close method is not called on its instance.


Solution

  • As @Antoniossss mentioned in the comments, listening for the ApplicationReadyEvent is a possible solution. I implemented it as follows:

    @EventListener(ApplicationReadyEvent.class)
    public void closeMyResource(ApplicationReadyEvent event) {
      InitHelper initHelper = event.getApplicationContext().getBean(InitHelper.class);
      initHelper.close();
    }