0

what is bean life cycle?why Inversion of control will not call destroy() method automatically,why we will call explicitly?

surya
  • 35
  • 3
  • 1
    Possible duplicate of [What is the lifecycle of spring bean?](https://stackoverflow.com/questions/13988720/what-is-the-lifecycle-of-spring-bean) – Mohit Tyagi Sep 09 '17 at 15:59
  • @MohitTyagi probably not as finalization is not mentioned in the dup target. – Jim Garrison Sep 09 '17 at 16:17
  • @surya Why do you need to control finalization. In Java it is never guaranteed that `finalize()` will be called and code that depends on it can fail in mysterious ways. Don't do it. Instead, read [Destruction Callbacks](https://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-lifecycle-disposablebean) in the Spring docs – Jim Garrison Sep 09 '17 at 16:20

1 Answers1

5

finalize() method has nothing to do with the Spring bean life cycle.
This method is called some time after an object is garbage collected.
Since it's difficult to predict when precisely this method is called, overriding it is considered bad practice.
In any case you should never call it directly.

The Spring bean lifecycle is described here - search for 'Destruction callbacks'.
In general, you annotate some method of your bean with @PreDestroy annotation and this method is called when the Spring container is being destroyed.

Alexander
  • 2,761
  • 1
  • 28
  • 33