Sunday, January 5, 2014

Spring Course: V10 Bean Scope & Life cycle

when you create a bean in beans.xml, you can add a Scope attribute which can take one of these 4 values: prototype, session, request, singleton

<bean id="person" class="com.caveofprogramming.spring.test.Person" scope="prototype">

the default is singleton which means whenever you use context.getBean(..) it will return the same bean (it will not create a new one).
Person person1 = (Person)context.getBean("person");
Person person2 = (Person)context.getBean("person");

if you want to change this behaviour and let spring returns a new bean for each context.getBean(..) then you should use the prototype scope.

another one is creating a bean for each session or a bean for each request.

we will talk about the other scope types later.

Creating a bean for each Session
when we create a bean for each session, we will have a problem, how can we inject a bean and the session is still not created.
in this case we use something called, scoped-proxy, which means we create a proxy to deal with
<bean id="...." class="...." scope="session"/>

this will use CGLIB for the proxy

Bean life Cycle
the bean has a life cycle, you can determine what part of the life cycle the bean should go, you can do that by implementing interfaces, for example if the bean implement BeanAwareName --> spring will make a call to the setBeanName() method.
implementing BeanPostProcessor --> PostProcessor() will be called

No comments:

Post a Comment