简体   繁体   English

Spring:如何干净地终止原型范围的bean?

[英]Spring: How to cleanly terminate prototype-scoped beans?

According to Spring documentation when a bean is scoped as "prototype" spring does not manage the complete lifecycle of its objects. 根据Spring文档,当bean的作用域为“prototype”时,spring不会管理其对象的完整生命周期。 More specifically the destruction lifecycle callbacks are not called. 更具体地说,不会调用销毁生命周期回调。 The client code must do the required clean ups. 客户端代码必须执行所需的清理。 The spring documentation also suggests to use a custom bean post-processor for this purpose. spring文档还建议为此目的使用自定义bean后处理器。 But the "BeanPostProcessor" interface only includes callback methods for before and after initialization of beans. 但是“BeanPostProcessor”接口仅包含bean初始化之前和之后的回调方法。 There is no method for desctruction callback. 没有解析回调的方法。 Then where and how to release resources obtained by prototype-scoped beans? 那么在何处以及如何释放由原型范围的bean获得的资源?

What you're looking for is the DestructionAwareBeanPostProcessor, it's a sub-interface of BeanPostProcessor. 您正在寻找的是DestructionAwareBeanPostProcessor,它是BeanPostProcessor的子接口。

You could create a new implementation of that interface yourself, or use one of its implementing classes, like CommonAnnotationBeanProcessor. 您可以自己创建该接口的新实现,或使用其实现类之一,如CommonAnnotationBeanProcessor。

The only clean way to terminate prototype-scoped bean is to explicitly call some of its "destroy"-methods to dispose resources. 终止原型范围bean的唯一干净方法是显式调用它的一些“destroy”方法来处理资源。 You can also use Phantom References . 您也可以使用幻影参考 Here is more info on different types of references. 以下是有关不同类型参考的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM