Step 2- Spring Bean

All the objects of application, which are managed by IOC containers are called beans.

Spring bean contains 3 things- 

1- Instantiation 

2-Life cycle details 

3-Dependency management

Code Example

1- XML Ways

A- Class –

public class MyBean {
    
    // Properties of the bean
    private String name;
    private int age;
    
    // Constructor
    public MyBean(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    // Getter and setter methods for properties
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int age) {
        this.age = age;
    }
    
    // Initialization method
    public void init() {
        // Perform any initialization tasks
        System.out.println("Initializing MyBean...");
    }
    
    // Destruction method
    public void cleanup() {
        // Perform any cleanup tasks
        System.out.println("Destroying MyBean...");
    }
}

B- Bean XML file

<bean id="myBean" class="com.example.MyBean" init-method="init" destroy-method="cleanup">
 <property name="name" value="John" /> 
<property name="age" value="30" />
 </bean>

2- Annotations Example-

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class MyBean implements InitializingBean, DisposableBean {
    
    // Properties of the bean
    private String name;
    private int age;
    
    // Constructor
    public MyBean(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    // Getter and setter methods for properties
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int age) {
        this.age = age;
    }
    
    // Initialization method
    public void afterPropertiesSet() throws Exception {
        // Perform any initialization tasks
        System.out.println("Initializing MyBean...");
    }
    
    // Destruction method
    public void destroy() throws Exception {
        // Perform any cleanup tasks
        System.out.println("Destroying MyBean...");
    }
}

Spring bean scopes – there are 5 scopes.

A- Singleton – One instance per IOC container

B- Prototype – Many instances 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

Here’s a comparison of the five Spring bean scopes:

ScopeInstances createdLifecycleAccessInjection
Singleton1Created once, reused throughout the applicationThread-safeSame instance injected into all dependent beans
PrototypeAs many as requestedCreated on every requestNot thread-safeNew instance injected into every dependent bean
RequestOne per HTTP requestCreated once per requestThread-safeSame instance injected into all dependent beans for a given request
SessionOne per HTTP sessionCreated once per sessionThread-safeSame instance injected into all dependent beans for a given session
Global SessionOne per global HTTP sessionCreated once per global sessionThread-safeSame instance injected into all dependent beans for a given global session


Spring bean life cycle – 
there are 2 things,

A- Initialization –

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)

Code Example-

public class MyBean implements BeanNameAware, BeanClassLoaderAware, BeanFactoryAware, InitializingBean, DisposableBean {

    private String myProperty;

    // Step 1: Bean instantiation
    public MyBean() {
        System.out.println("Bean instantiated");
    }

    // Step 2: Dependency Injection
    public void setMyProperty(String myProperty) {
        this.myProperty = myProperty;
        System.out.println("Property " + myProperty + " set on bean");
    }

    // Step 3: BeanNameAware interface - setBeanName() method
    @Override
    public void setBeanName(String name) {
        System.out.println("Bean name set to " + name);
    }

    // Step 4: BeanClassLoaderAware interface - setBeanClassLoader() method
    @Override
    public void setBeanClassLoader(ClassLoader classLoader) {
        System.out.println("Bean class loader set to " + classLoader);
    }

    // Step 5: BeanFactoryAware interface - setBeanFactory() method
    @Override
    public void setBeanFactory(BeanFactory beanFactory) {
        System.out.println("Bean factory set to " + beanFactory);
    }

    // Step 6: BeanPostProcessor - postProcessBeforeInitialization() method
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessBeforeInitialization called for bean " + beanName);
        return bean;
    }

    // Step 7: InitializingBean interface - afterPropertiesSet() method
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("afterPropertiesSet called");
    }

    // Step 8: Custom initialization method specified in configuration file
    public void init() {
        System.out.println("Custom initialization method called");
    }

    // Step 9: BeanPostProcessor - postProcessAfterInitialization() method
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessAfterInitialization called for bean " + beanName);
        return bean;
    }

    // Step 10: DisposableBean interface - destroy() method
    @Override
    public void destroy() throws Exception {
        System.out.println("destroy called");
    }

    // Step 11: Custom destroy method specified in configuration file
    public void customDestroy() {
        System.out.println("Custom destroy method called");
    }
}

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- Steps 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”/>
Advertisement