Sobes.tech
Junior — Middle

Does Spring have control over the bean lifecycle when using prototype creation mode?

sobes.tech AI

Answer from AI

When using the prototype mode in Spring, the container creates a new bean instance each time it is requested. However, Spring does not manage the full lifecycle of such beans: it creates the bean and calls initialization methods, but does not call destruction methods (destroy), as it does not track them after issuance.

This means that if a bean in prototype mode requires resource release, the responsibility for calling cleanup methods falls on the developer.

Example:

@Component
@Scope("prototype")
public class MyPrototypeBean {
    @PostConstruct
    public void init() {
        System.out.println("Initializing prototype bean");
    }

    @PreDestroy
    public void cleanup() {
        System.out.println("Cleaning up prototype bean");
    }
}

In this case, the cleanup method will not be called automatically by Spring.

Does Spring have control over the bean lifecycle when… - sobes.tech