Sobes.tech
Middle

What happens if you try to get the same bean from ApplicationContext?

sobes.tech AI

Answer from AI

If a bean has a scope of singleton (default), then the same instance of the object will be returned upon each request to the ApplicationContext.

If a bean has a scope of prototype, then a new instance of the object will be created and returned each time.

Other scopes (for example, request, session in web applications) also influence which bean instance will be obtained.

Example for singleton:

// Bean with singleton scope (default)
@Component
public class SingletonBean {
    private static int count = 0;
    private int instanceId;

    public SingletonBean() {
        count++;
        instanceId = count;
        System.out.println("SingletonBean instance created: " + instanceId);
    }

    public int getInstanceId() {
        return instanceId;
    }
}

Getting the bean multiple times:

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

SingletonBean bean1 = context.getBean(SingletonBean.class);
SingletonBean bean2 = context.getBean(SingletonBean.class);

System.out.println("Bean 1 instance ID: " + bean1.getInstanceId()); // Output: Bean 1 instance ID: 1
System.out.println("Bean 2 instance ID: " + bean2.getInstanceId()); // Output: Bean 2 instance ID: 1

context.close();

Only one creation message will be printed in the console: SingletonBean instance created: 1.

Example for prototype:

// Bean with prototype scope
@Component
@Scope("prototype")
public class PrototypeBean {
    private static int count = 0;
    private int instanceId;

    public PrototypeBean() {
        count++;
        instanceId = count;
        System.out.println("PrototypeBean instance created: " + instanceId);
    }

    public int getInstanceId() {
        return instanceId;
    }
}

Getting the bean multiple times:

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

PrototypeBean bean1 = context.getBean(PrototypeBean.class);
PrototypeBean bean2 = context.getBean(PrototypeBean.class);

System.out.println("Bean 1 instance ID: " + bean1.getInstanceId()); // Output: Bean 1 instance ID: 1
System.out.println("Bean 2 instance ID: " + bean2.getInstanceId()); // Output: Bean 2 instance ID: 2

context.close();

Two creation messages will be printed: PrototypeBean instance created: 1 and PrototypeBean instance created: 2.

Thus, the result of obtaining the same bean depends on its scope, as defined in the Spring configuration.

What happens if you try to get the same bean from… - sobes.tech