SpringBoot:在上次使用/初始化阶段后销毁bean
我有一个 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 在 A
和 B
之前初始化,并在 a
和 b< /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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如 @Antoniossss 在评论中提到的,监听
ApplicationReadyEvent
是一种可能的解决方案。我的实现如下:As @Antoniossss mentioned in the comments, listening for the
ApplicationReadyEvent
is a possible solution. I implemented it as follows: