Sobes.tech
Middle+

What are prototype beans used for in Spring? Provide an example of usage.

sobes.tech AI

Answer from AI

In Spring, beans with the prototype scope are created anew each time they are requested from the container, unlike singletons, which are created once at application startup.

This is useful when a new instance of an object is needed for each use, for example, to store state that is unique to each call.

Example of usage:

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

@Service
public class UserService {
    @Autowired
    private ApplicationContext context;

    public void process() {
        UserSession session = context.getBean(UserSession.class);
        // each call to getBean returns a new instance
        session.setSessionId(UUID.randomUUID().toString());
        // work with the session
    }
}

Thus, prototype beans allow creating objects with a unique state for each request, which is not possible with singleton scope.

What are prototype beans used for in Spring? Provide… - sobes.tech