Spring prototype bean 怎么了

直接进入主题:

There is one quite important thing to be aware of when deploying a bean in the prototype scope, in that the lifecycle of the bean changes slightly. Spring cannot (and hence does not) manage the complete lifecycle of a prototype bean: the container instantiates, configures, decorates and otherwise assembles a prototype object, hands it to the client and then has no further knowledge of that prototype instance. This means that while initialization lifecycle callback methods will be (and are) called on all objects regardless of scope, in the case of prototypes, any configured destruction lifecycle callbacks will not be called. It is the responsibility of the client code to clean up prototype scoped objects and release any expensive resources that the prototype bean(s) are holding onto. (One possible way to get the Spring container to release resources used by singleton-scoped beans is through the use of a bean post processor which would hold a reference to the beans that need to be cleaned up.)-----引用官方文档

大意是,“singleton” 的bean的初始化和销毁整个生命周期都是由spring容器来管理的,但是对于“prototype”的bean,spring容器只负责实例化,提供给你用,剩下的你来搞定。是所以,“prototype” bean的销毁就需要程序员处理好。


查看,BeanPostProcessor接口,有2个方法:

1.//对实例化bean进行包装,该方法执行的时机是在bean初始化回调方法执行之前。(before any bean initialization callbacks (like InitializingBean's afterPropertiesSet  or a custom init-method).)

Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException; 


2.//与1相反,是在之后执行

Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;


查看,DestructionAwareBeanPostProcessor接口,继承BeanPostProcessor接口,添加了一个方法:

void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException;

但是很可惜,Like DisposableBean's and a custom destroy method, this callback just applies tosingleton beans in the factory (including inner beans).只能用于单例beans的销毁前执行的动作,和destroy-method作用一样。


有什么好方法呢?还是根本不用去操作?


当天晚上,恍然大悟...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值