Sobes.tech
Junior — Middle

Can you demonstrate an example where the prototype scope is used for beans in Spring?

sobes.tech AI

Answer from AI

In Spring, the prototype scope (scope = "prototype") is used when a new bean instance needs to be created for each request. Unlike singleton, where the same object is reused, the prototype guarantees that each call receives a fresh object.

Example:

@Component
@Scope("prototype")
public class UserSession {
    private final String sessionId = UUID.randomUUID().toString();

    public String getSessionId() {
        return sessionId;
    }
}

// In another bean
@Component
public class UserService {
    @Autowired
    private ApplicationContext context;

    public void printSessionId() {
        UserSession session1 = context.getBean(UserSession.class);
        UserSession session2 = context.getBean(UserSession.class);
        System.out.println(session1.getSessionId()); // unique ID
        System.out.println(session2.getSessionId()); // different unique ID
    }
}

Here, each call to context.getBean(UserSession.class) creates a new UserSession object with a unique sessionId.

Can you demonstrate an example where the prototype… - sobes.tech