Sobes.tech
Junior — Middle

How does changing the bin area in Spring affect the call of methods annotated with @PreDestroy?

sobes.tech AI

Answer from AI

In Spring, the scope of a bean defines how long an instance of the bean exists and when it is destroyed. The @PreDestroy annotation marks a method that is called before the bean is destroyed.

  • For singleton scope (default), the bean is created once per container, and the method with @PreDestroy is called when the Spring context is shut down (e.g., when the application stops).
  • For prototype scope, Spring creates a new bean instance for each request, but does not manage its lifecycle fully, so the method with @PreDestroy is not called automatically — responsibility for calling it lies with the developer.
  • For request, session, and other web-related scopes, the @PreDestroy method is called when the respective scope ends (e.g., at the end of an HTTP request or session).

Thus, changing the bean's scope affects the timing and occurrence of @PreDestroy method calls: for singleton and managed lifecycle scopes, the method is called automatically, for prototype — not.

How does changing the bin area in Spring affect the… - sobes.tech