Spring prototype bean 怎么了

本文探讨了Spring框架中Prototype作用域的Bean生命周期管理问题,重点解释了Prototype Bean与Singleton Bean生命周期的不同之处,以及如何处理Prototype Bean的销毁过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

直接进入主题:

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作用一样。


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


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

### Spring Framework Prototype Scope Bean Usage and Behavior In the context of the Spring framework, beans defined with `prototype` scope ensure that each time such a bean is requested from the Spring container, a new instance is created. This contrasts sharply with singleton-scoped beans where only one shared instance exists per application context. When using prototype-scoped beans within another bean via property setter injection or constructor arguments, every request for the containing bean results in creation of a fresh prototype bean instance[^1]. However, once instantiated through dependency injection mechanisms provided by Spring's Inversion of Control (IoC), these instances do not get managed further regarding lifecycle events like initialization callbacks (`@PostConstruct`) or destruction callbacks (`@PreDestroy`). Developers must manage their lifecycles manually outside the container if required. For demonstration purposes: ```java // Define a simple service class as prototype scoped. @Service @Scope("prototype") public class MyPrototypeService { private final String message; public MyPrototypeService() { this.message = UUID.randomUUID().toString(); } public void sayHello(){ System.out.println("Hello! I am a unique instance identified by " + this.message); } } // A controller utilizing the above-defined prototype service. @RestController @RequestMapping("/test") public class TestController { @Autowired private ApplicationContext applicationContext; @GetMapping("/proto") public ResponseEntity<String> testPrototypeScope(){ // Obtain two separate instances of our prototype service. MyPrototypeService firstInstance = applicationContext.getBean(MyPrototypeService.class); MyPrototypeService secondInstance = applicationContext.getBean(MyPrototypeService.class); // Demonstrating both services hold different identities. firstInstance.sayHello(); secondInstance.sayHello(); return ResponseEntity.ok("Checked two distinct prototype scoped beans."); } } ``` This code snippet illustrates how obtaining a prototype-scoped bean twice yields distinctly individual objects even though they originate from identical definitions inside the same web request cycle. Each call to `applicationContext.getBean()` produces its own isolated copy of `MyPrototypeService`.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值