一个原型bean的例子:
结果是 注解的@PreDestroy的方法close()没有执行,而如果是单例bean 的singleton则会执行
那若想销毁Spring的原型bean应该怎么办呢?
我注意到我的原型范围的Spring bean的@PreDestroy钩子没有被执行.
我已经读过here,这实际上是设计的. Spring容器将销毁单例bean,但不会销毁原型bean.我不清楚为什么.如果Spring容器将创建我的原型bean并执行其@PostConstruct钩子,为什么在容器关闭时它也不会破坏我的bean?一旦我的Spring容器关闭,继续使用它的任何bean都有意义吗?我看不到你想要在完成bean之前关闭容器的场景.甚至可以在容器关闭后继续使用原型Spring bean吗?
上面描述了我的主要问题的令人费解的背景:如果Spring容器没有破坏原型bean,那是否意味着可能发生内存泄漏?或者原型bean会在某些时候被垃圾收集?
春季文件指出:
The client code must clean up prototype-scoped objects and release
expensive resources that the prototype bean(s) are holding. To get the
Spring container to release resources held by prototype-scoped beans,