SpringBoot:在上次使用/初始化阶段后销毁bean

发布于 2025-01-12 07:59:10 字数 874 浏览 4 评论 0原文

我有一个 Closeable bean,仅在应用程序初始化期间使用,但稍后不再使用。它打开初始化期间使用的资源。我希望在最后一次使用该对象后尽早调用 close 方法。是否可以自动销毁物体。

示例

@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());
  }
}

预期行为

InitHelper bean 在 AB 之前初始化,并在 ab< /code> 已完成。

实际行为

不会在其实例上调用 InitHelper.close 方法。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尬尬 2025-01-19 07:59:10

正如 @Antoniossss 在评论中提到的,监听 ApplicationReadyEvent 是一种可能的解决方案。我的实现如下:

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

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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文