Sobes.tech
Senior

Where in real life is prototype scope used?

sobes.tech AI

Answer from AI

Prototype scope in Java, especially in Spring, is used when a new bean instance needs to be created for each request. In real life, this is convenient, for example, for objects that store state specific to a single user or operation and should not be shared between different clients.

Example: In a web application, you have a bean that stores user session data or request-specific parameters. If this bean is a singleton, the data will be shared among all users, which can lead to errors. Using prototype scope, each request gets a separate instance.

@Component
@Scope("prototype")
public class UserSession {
    private String userId;
    // getters and setters
}

Thus, prototype scope is useful for beans with a short lifecycle and state that is unique to each use.

Where in real life is prototype scope used? — Java - sobes.tech