Sobes.tech
Junior — Middle

If two classes access the same instance of a bean, will two separate objects be created?

sobes.tech AI

Answer from AI

If two classes access the same bean instance in the context, for example, in the Spring Framework, then the same object (one bean instance) is created, not two separate ones. This is because, by default, beans in Spring have a singleton scope, meaning one instance for the entire application context.

Example:

@Component
public class MyBean {
    // ...
}

@Component
public class ClassA {
    private final MyBean myBean;
    public ClassA(MyBean myBean) {
        this.myBean = myBean;
    }
}

@Component
public class ClassB {
    private final MyBean myBean;
    public ClassB(MyBean myBean) {
        this.myBean = myBean;
    }
}

In this example, ClassA and ClassB receive the same instance of MyBean.

If the bean is configured with a different scope (for example, prototype), then a new object is created with each request.

If two classes access the same instance of a bean… - sobes.tech