Step 3- Spring Bean

All the objects of application, which are managed by IOC containers are called beans.
Spring bean contains 3 things- 
– instantiation 
-life cycle details 
-dependency management

 

Spring bean scopes – there are 5 scopes

a- singleton – one instance per IOC container

b- prototype – many instance per IOC container

c- request – only for web application, instance per http request

d- session-only for web application, instance per http session

e- global session only for web application, instance per global http session

Spring bean life cycle –
there are 2 things,
A- Initialisation –
B- Destruction-
Detailed step by step bean lifecycle in spring framework-

Step1- spring container finds the bean definition from configuration file.
Step2- Bean is instantiated.
Step3- DI is applied from specified properties.
Step4- If Bean class implements BeanNameAware interface, setBeanName() is called by passing bean’s I’d. (optional)
Step5- If BeanClassLoaderAware is implemented, setBeanClassLoader() is called by passing ClassLoader object. (optional)
Step6- If BeanFactoryAware is implemented, setBeanFactory() is called by passing BeanFactory object. (optional)
Step7- If BeanPostProcessors object is in BeanFactory, postProcessBeforeInitialization() is called even before setting property for bean.(optional)
Step 8- If InitialisingBean is implemented, afterPropertiesSet () is called after setting bean properties.(optional)
Step9- If init-method is specified in configuration file, method is called for bean.(optional)
Step10- If BeanPostProcessors are present, postProcessAfterInitialization() is called. (optional)
Step11- If DisposableBean is implemented, destroy () is called.(optional)
Step12- If destroy-method is specified in configuration file, method is called for bean.(optional)
Spring callBack methods-

A callback method is called when an event occurs.

Spring uses 2 callback methods-
A- post-initialization callback methods
B- pre-destroy callback methods
1- Step 8 & 9 are post-initialization callback methods.
Step8 syntax-
Class Test implements InitialisingBean {
public void afterPropertiesSet(){
}}
Step 9 syntax-
Class Test{
public void init(){
}}
2- Step 11 & 12 are pre-destroy callback methods
Step11- Class Test implements DisposableBean {
public void destroy(){
}}
Step 12 syntax-
Class Test{
public void destroy(){
}}
Spring Bean Inheritance – Spring provides facility that child bean definition can inherits data from parent bean definition.
Syntax –
<bean id=”Pbean” class=”ParentBean”/>
<bean id=”Cbean” class=”ChildBean” parent=”Pbean”/>
Advertisements