Sobes.tech
Junior — Middle

Explain why the @PreDestroy annotation is not suitable for use with the Prototype pattern in Spring?

sobes.tech AI

Answer from AI

The @PreDestroy annotation in Spring is used to indicate a method that should be called before a bean is destroyed. However, for beans with a Prototype scope, Spring does not fully manage the lifecycle — it creates the object and hands it to the client, but does not track when the bean is no longer needed or invoke destruction methods.

Therefore, @PreDestroy will not work for prototype beans, as Spring does not automatically call the destruction method. The responsibility for cleaning up such objects lies with the client code, which must explicitly call the necessary methods or release resources.

Example:

@Component
@Scope("prototype")
public class MyPrototypeBean {
    @PreDestroy
    public void cleanup() {
        System.out.println("Cleanup called");
    }
}

In this case, cleanup() will not be called automatically when the bean is no longer in use.

Explain why the @PreDestroy annotation is not… - sobes.tech