Sobes.tech
Junior — Middle

How to initiate the destruction of a Prototype instance created with Spring?

sobes.tech AI

Answer from AI

The Spring container manages the lifecycle of singleton-scoped beans, including their destruction. For prototype-scoped beans, Spring creates instances on request but does not track their lifecycle after creation, so automatic destruction methods are not called.

To initiate the destruction of a prototype instance, it must be done manually. This is usually achieved by calling a method annotated with @PreDestroy or another custom method responsible for resource cleanup.

Example:

@Component
@Scope("prototype")
public class MyPrototypeBean {
    public void cleanup() {
        // cleanup code, resource release
    }
}

// Somewhere in the code where the bean is obtained:
MyPrototypeBean bean = context.getBean(MyPrototypeBean.class);
// Use the bean
// ...
// Explicitly call the cleanup method
bean.cleanup();

For automatic invocation of destruction methods, you can implement the DisposableBean interface and call the destroy() method manually.

In summary: for prototype beans in Spring, destruction of the instance and invocation of cleanup methods must be initiated manually, as the container does not manage their lifecycle after creation.

How to initiate the destruction of a Prototype… - sobes.tech