CodeGym /Courses /Module 5. Spring /Bean scopes (singleton, prototype, etc.)

Bean scopes (singleton, prototype, etc.)

Module 5. Spring
Level 2, Lesson 5
Available

Scope (Scope) in Spring is a rule that defines a bean's lifecycle: when to create a new instance, how long to keep it, and when to destroy it. Think of it like resource management rules — some resources you create once and reuse, others need a fresh instance on every access.

Scopes matter because different parts of your app may have different requirements for object creation. For example:

  • For stateless services, we want to use the same instance across the whole app.
  • For objects that hold unique data per HTTP request, we need a new instance for each request.

In a real project, understanding scopes helps you manage resources flexibly and improves app performance.


Standard Spring scopes

Let's go over the main Spring scopes:

  1. Singleton (default)
  2. Prototype
  3. Request
  4. Session
  5. Application

Singleton: "One for all"

Singleton is the default scope. When a bean is marked with this scope (or not marked at all), Spring creates only one instance of the bean per ApplicationContext. That instance is reused every time it's requested.


@Component
public class SingletonExample {
    public SingletonExample() {
        System.out.println("Singleton bean created");
    }
}

If you inject the bean above into two different parts of the app, for example into two different classes, Spring will create one instance and pass the same object everywhere. Example:


@Component
public class MyService {

    private final SingletonExample singletonExample;

    @Autowired
    public MyService(SingletonExample singletonExample) {
        this.singletonExample = singletonExample;
        System.out.println("MyService received the SingletonExample bean");
    }
}

@Component
public class AnotherService {

    private final SingletonExample singletonExample;

    @Autowired
    public AnotherService(SingletonExample singletonExample) {
        this.singletonExample = singletonExample;
        System.out.println("AnotherService received the SingletonExample bean");
    }
}

Result:


Singleton bean created
MyService received the SingletonExample bean
AnotherService received the SingletonExample bean

Prototype: "A new bean per request"

Prototype is the scope you use when you need a new instance of the bean on every request. It's useful if the bean holds state that changes depending on business logic.


@Component
@Scope("prototype")
public class PrototypeExample {
    public PrototypeExample() {
        System.out.println("Prototype bean created");
    }
}

If two different components request PrototypeExample, Spring will create two separate instances.


@Component
public class MyPrototypeService {

    private final PrototypeExample prototypeExample;

    @Autowired
    public MyPrototypeService(PrototypeExample prototypeExample) {
        this.prototypeExample = prototypeExample;
        System.out.println("MyPrototypeService received the PrototypeExample bean");
    }
}

@Component
public class AnotherPrototypeService {

    private final PrototypeExample prototypeExample;

    @Autowired
    public AnotherPrototypeService(PrototypeExample prototypeExample) {
        this.prototypeExample = prototypeExample;
        System.out.println("AnotherPrototypeService received the PrototypeExample bean");
    }
}

Result:


Prototype bean created
MyPrototypeService received the PrototypeExample bean
Prototype bean created
AnotherPrototypeService received the PrototypeExample bean

Request: "New bean for each HTTP request"

This scope is used in web applications. A separate bean instance is created for each HTTP request.


@Component
@Scope("request")
public class RequestScopedBean {
    public RequestScopedBean() {
        System.out.println("Request bean created");
    }
}
⚠️ Warning:

you can use this scope only in an app with web context support, for example Spring MVC.

Session: "One bean per user session"

Session scope creates a bean that's unique to a user's session.


@Component
@Scope("session")
public class SessionScopedBean {
    public SessionScopedBean() {
        System.out.println("Session bean created");
    }
}

Application: "One bean for the whole application context"

This scope is similar to singleton, but specific to web apps with multiple servlets. The bean is created once and used across all servlets of the application.


How to configure scopes?

You can configure scopes with the @Scope annotation. Here's an example of specifying a scope for a bean:


@Component
@Scope("prototype") // Specify the scope for this bean
public class MyPrototypeBean {
    // Bean logic
}

For web-oriented scopes (request, session, application) you can use the same approach.

How to choose the right scope?

Singleton is perfect for stateless services. For example, an email-sending service — it just performs an action and doesn't store data.

Prototype is needed when each user needs their own instance. Imagine a registration form — everyone has their own data.

Request/Session help you work with web data. For example, a shopping cart in an online store lives within a user's session.

Note: choosing a scope affects memory and performance. Be careful with prototype — each new instance uses memory, and you need to free it appropriately.

Common mistakes when using scopes

  1. Using prototype beans inside singleton beans: if you inject a prototype bean into a singleton bean via DI,
  2. Spring will create only one instance of the prototype bean and attach it to the singleton. To fix this you can use the ObjectFactory interface or the @Lookup annotation.

  3. Trying to use web-oriented scopes in a non-web application: in this case you'll get a No Scope Registered for ScopeName error.


Now you can confidently work with scopes in the Spring Framework, using them to build flexible and scalable applications! In the next lecture we'll cover the @Configuration and @Bean annotations, which will help you better manage configurations and bean factories.

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION