WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

RESTful Web Services · Intermediate · question 34 of 100

What is the difference between a singleton and a prototype scope in Spring?

📕 Buy this interview preparation book: 100 RESTful Web Services questions & answers — PDF + EPUB for $5

In Spring, scope refers to the lifecycle of a bean, which determines how many instances of the bean will be created and when. There are several scopes available in Spring, including singleton and prototype.

Singleton Scope: In singleton scope, only one instance of the bean is created per Spring container, and this instance is shared across all requests for the bean. This means that every time a bean is requested, the same instance is returned. This can be useful for stateless beans that do not maintain any internal state between requests. Here’s an example of how to define a singleton bean in Spring:

    @Service
    @Scope("singleton")
    public class MyService {
        // bean implementation
    }

Prototype Scope: In prototype scope, a new instance of the bean is created every time it is requested. This means that the instance is not shared across requests, and any state that is maintained by the bean is reset every time a new instance is created. This can be useful for stateful beans that maintain internal state between requests. Here’s an example of how to define a prototype bean in Spring:

    @Service
    @Scope("prototype")
    public class MyService {
        // bean implementation
    }

In summary, the main difference between singleton and prototype scope in Spring is that singleton scope creates only one instance of a bean and shares it across all requests, while prototype scope creates a new instance of the bean for each request. The choice of scope depends on the specific requirements and constraints of the application.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic RESTful Web Services interview — then scores it.
📞 Practice RESTful Web Services — free 15 min
📕 Buy this interview preparation book: 100 RESTful Web Services questions & answers — PDF + EPUB for $5

All 100 RESTful Web Services questions · All topics