33

I have a doubt about the number of instances that will be created in the scenario mentioned below, when Spring Framework is used:

The bean configuration is like this

<bean id="a" class="A">
    <property name="b" ref="b"/>
</bean>

<bean id="b" class="B" scope="session"/> or

<bean id="b" class="B" scope="prototype"/>

By default, bean "a" has singleton scope. So there is a singleton bean with a reference to a bean with session scope or prototype scope.

In this case, if there are 2 simultaneous requests to the application, then how many instances of A will be created and how many instances of B will be created?

It will be of great help if anyone can explain how this works.

Thanks, Divya

Alexander Ziubin
  • 35
  • 1
  • 2
  • 7
user1477232
  • 457
  • 1
  • 8
  • 17
  • 1
    Read the docs http://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s04.html#beans-factory-scopes-global-session – Bart Jul 28 '14 at 17:25
  • To answer your question. It all depends on the number of sessions. – Bart Jul 28 '14 at 17:28

3 Answers3

47

The singleton scope

When a bean is a singleton, only one shared instance of the bean will be managed, and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned by the Spring container.

To put it another way, when you define a bean definition and it is scoped as a singleton, then the Spring IoC container will create exactly one instance of the object defined by that bean definition. This single instance will be stored in a cache of such singleton beans, and all subsequent requests and references for that named bean will result in the cached object being returned.

The session scope

With the above bean definition in place, the Spring container will create a brand new instance of the bean , for the lifetime of a single HTTP Session.

According to Spring framework reference, a different approach needs to be followed in cases where a class which "lives longer"(singleton bean in this case) needs to be injected with another class having a comparatively shorter life-span(session-scoped bean). The approach is different for prototype & singleton scope though.

In your XML, what we want is that the singletonBean instance should be instantiated only once, and it should be injected with sessionBean. But since sessionBean is session-scoped(which means it should be re-instantiated for every session), the configuration is ambiguous(as the dependencies are set at instantiation time and the session scoped value can change later also).

So instead of injecting with that class, its injected with a proxy that exposes the exact same public interface as sessionBean. The container injects this proxy object into the singletonBean bean, which is unaware that this sessionBean reference is a proxy. Its specified by writing this tag in the sessionBean:

<aop:scoped-proxy/>

XML Configuration:

<bean name="singletonBean" class="somepkg.SingletonBean">
<property name="someProperty" ref="sessionBean"/>
</bean>

<bean name="sessionBean" class="somepkg.SessionBean" scope="session">
<aop:scoped-proxy/>
</bean>

When a singletonBean instance invokes a method on the dependency-injected sessionBean object, it actually is invoking a method on the proxy. The proxy then fetches the real sessionBean object from (in this case) the HTTP Session, and delegates the method invocation onto the retrieved real sessionBean object.

Alse please refer this for more info.

Singleton beans with prototype-bean dependencies

Lookup Method Injection

When you use singleton-scoped beans with dependencies on prototype beans, be aware that dependencies are resolved at instantiation time. Thus if you dependency-inject a prototype-scoped bean into a singleton-scoped bean, a new prototype bean is instantiated and then dependency-injected into the singleton bean. The prototype instance is the sole instance that is ever supplied to the singleton-scoped bean.

However, suppose you want the singleton-scoped bean to acquire a new instance of the prototype-scoped bean repeatedly at runtime. You cannot dependency-inject a prototype-scoped bean into your singleton bean, because that injection occurs only once, when the Spring container is instantiating the singleton bean and resolving and injecting its dependencies.

<!-- a stateful bean deployed as a prototype (non-singleton) -->
<bean id="command" class="fiona.apple.AsyncCommand" scope="prototype">
  <!-- inject dependencies here as required -->
</bean>

<!-- commandProcessor uses statefulCommandHelper -->
<bean id="commandManager" class="fiona.apple.CommandManager">
  <lookup-method name="createCommand" bean="command"/>
</bean>

Lookup method injection is the ability of the container to override methods on container managed beans, to return the lookup result for another named bean in the container. The lookup typically involves a prototype bean as in the scenario described in the preceding section. The Spring Framework implements this method injection by using bytecode generation from the CGLIB library to generate dynamically a subclass that overrides the method.

Refer lookup method injection.

Follow for more detailed example and information.

Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
  • 1
    Thanks.It is clear now .If suppose class "A" is scoped as "Prototype" than "singleton " then how will the same scenario be ?Because prototype also creates a new instance for every request.How is it different from session scope ? – user1477232 Jul 28 '14 at 18:04
  • @user1477232 Answer modified for Prototype dependency as well. Spring provides 'Lookup method' for the same. – Ankur Singhal Jul 29 '14 at 01:41
  • @ankur-singhal: First of all thank you for your detailed explanation. My question is what will happen if we try to load the xml with bean configuration given by "user1477232". Do we get any exception in runtime? – Lathy Jul 29 '15 at 10:34
3

If we use the way as mentioned in question spring IOC will create always return the same object as singleton, In order to inject prototype bean inside singleton we have two way

1) Lookup method injection

2) Scoped Proxies

see more detail here

Surya
  • 416
  • 4
  • 7
  • 26
0

First of all, I don't think it is valid to define a bean, both with session and prototype scopes at the same time with the same bean id.

How many instances created for singleton bean referring to a prototype bean?

In your case: one

In general: depending on how you access the bean:

One

@Component
class MySingletonBean{
    @Autowired
    MyPrototypeBean b;
}

Two

@Component
class MySingletonBean{
    @Autowired
    MyPrototypeBean b;

    @Autowired
    MyPrototypeBean bSecondInstance;

}

Or more

@Component
class MySingletonBean{
    @Autowired
    javax.inject.Provider<MyPrototypeBean> providerOfB;

    void accessMultipleInstances(){
       MyPrototypeBean bInstance1 = providerOfB.get();
       MyPrototypeBean bInstance2 = providerOfB.get();
       MyPrototypeBean bInstance3 = providerOfB.get();
       //.....

    }

}

Note: MyPrototypeBean is considered to have been marked with: @Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE). If you omit it ,then in all the above cases you will reference the same singleton instance.

Regarding session-scoped bean:

One per session.

According to this answer spring will automatically create a proxy which targets different instance depending on the session.

This means that in all the above cases you will get access to the same instance while you are on the same session.

Regarding the provided xml config:

To me it would be more meaningful something like this:

<bean id="a" class="A">
    <property name="b" ref="b"/>
    <property name="b2" ref="b2"/>
</bean>
<bean id="b" class="B" scope="session"/> or
<bean id="b2" class="B" scope="prototype"/>

In which case you would get one instance per session for b and one and only instance for b2 because you use it from a singleton and you don't use the provider or some similar pattern.

Marinos An
  • 9,481
  • 6
  • 63
  • 96