2

I found out that @PreDestroy only work with singleton scoped bean. I was thinking what could go wrong if we use it with prototype scoped bean. Anything at all??? I dont think so. I think this is just not implemented in spring as they would have to keep the references to all the beans created. Tell me if i am wrong

varun
  • 684
  • 1
  • 11
  • 30

3 Answers3

4

Spring can only initialize/destroy beans it also controllers and basically prototype scoped beans aren't under the control of spring (after construction). It doesn't know when it is cleaned up, destroyed or what so ever. As such the @PreDestroy method isn't callable for prototype beans (as they do not have a clearly defined lifecycle like singletons or request scoped beans).

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
  • correct, but why their lifecycle are not managed by spring as spring created that bean it in the first place. – varun Dec 10 '13 at 08:43
  • 1
    Because spring has no way of knowing when the objects life is to be ended. It knows when life starts but not when it ends, hence the undefined lifecycle (as opposed to singleton, request, session scoped beans those are clearly defined). – M. Deinum Dec 10 '13 at 09:00
1

The @PreDestroy annotation does not belong to Spring, it’s located in the jsr250-api library jar under javax.annotation package.

By default, Spring will not aware of the @PreDestroy annotation. To enable it, you have to either register CommonAnnotationBeanPostProcessor or specify the <context:annotation-config /> in bean XML configuration file.

DimaSan
  • 12,264
  • 11
  • 65
  • 75
Vineet Kasat
  • 994
  • 7
  • 14
  • thanks for the info but that wasnt the point here. The point is that its handled by spring container and why its not called for non singleton beans. – varun Dec 10 '13 at 06:41
1

For "prototype" scoped beans, Spring does not call the @PreDestroy method.

Here is the answer from the Spring reference manual. Section 7.5.2

http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-factory-scopes-prototype

In contrast to the other scopes, Spring does not manage the complete lifecycle of a prototype bean: the container instantiates, configures, and otherwise assembles a prototype object, and hands it to the client, with no further record of that prototype instance.

Thus, although initialization lifecycle callback methods are called on all objects regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not called. 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, try using a custom bean post-processor, which holds a reference to beans that need to be cleaned up.