How to Use Bean Scopes in Spring Framework

1 min read

How to Use Bean Scopes in Spring Framework

In the Spring Framework, a bean scope determines the lifecycle and visibility of a bean within the Spring context. Spring offers several types of bean scopes to manage how and when beans are created and returned.

By default, all beans in Spring are singleton, but Spring provides other scopes for different use cases.

Available Bean Scopes in Spring

  1. Singleton (Default)
  2. Prototype
  3. Request (Web-aware only)
  4. Session (Web-aware only)
  5. Application (Web-aware only)
  6. Websocket (Web-aware only)

Let’s walk through the most commonly used ones: Singleton and Prototype, and see how the Request and Session scopes work in web applications.


1. Singleton Scope (Default)

  • One instance per Spring container.
@Component
@Scope("singleton") // or omit as it's the default
public class MySingletonBean {
    public MySingletonBean() {
        System.out.println("Singleton Bean Created");
    }
}

Usage:

@RestController
public class TestController {

    @Autowired
    private MySingletonBean mySingletonBean;

    @GetMapping("/singleton")
    public String testSingleton() {
        return mySingletonBean.toString();
    }
}

You will see that the bean is created once and reused for every request.


2. Prototype Scope

  • A new instance every time the bean is requested.
@Component
@Scope("prototype")
public class MyPrototypeBean {
    public MyPrototypeBean() {
        System.out.println("Prototype Bean Created");
    }
}

Usage:

@RestController
public class TestController {

    @Autowired
    private ApplicationContext context;

    @GetMapping("/prototype")
    public String testPrototype() {
        MyPrototypeBean bean = context.getBean(MyPrototypeBean.class);
        return bean.toString();
    }
}

Every time you call /prototype, a new bean instance is created.


3. Request Scope (Web Applications Only)

  • One instance per HTTP request.
@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyRequestBean {
    public MyRequestBean() {
        System.out.println("Request Scoped Bean Created");
    }
}

Usage:

@RestController
public class RequestController {

    @Autowired
    private MyRequestBean requestBean;

    @GetMapping("/request")
    public String handleRequest() {
        return requestBean.toString();
    }
}

A new bean is created for each HTTP request.


4. Session Scope

  • One instance per user session.
javaCopyEdit@Component
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MySessionBean {
    public MySessionBean() {
        System.out.println("Session Scoped Bean Created");
    }
}

Usage:

@RestController
public class SessionController {

    @Autowired
    private MySessionBean sessionBean;

    @GetMapping("/session")
    public String handleSession() {
        return sessionBean.toString();
    }
}

Each user session gets its own instance of the bean.


Summary

ScopeDescriptionWeb Only?
SingletonOne instance per Spring containerNo
PrototypeNew instance every time it’s requestedNo
RequestOne instance per HTTP requestYes
SessionOne instance per user sessionYes
ApplicationOne per ServletContextYes
WebsocketOne per WebSocket sessionYes

Testing & Observing Scopes

To observe the scope behavior clearly, watch the console logs. Each constructor log will indicate whether a new bean instance is created.


Conclusion

Spring provides flexible bean scopes to help you manage bean lifecycles according to your application’s needs. By understanding and using these scopes effectively, you can optimize memory usage and maintain clean separation of concerns in your codebase.

🤞 Never miss a story from us, get weekly updates to your inbox!

Leave a Reply

Your email address will not be published. Required fields are marked *