Topic 2:- Spring Bean (3 parts, 5 types of scope and 12 steps of lifecycle, 2 callback methods)

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

Spring bean contains 3 things- 

1- Instantiation  – creation of an object of a class (bean) by the Spring IoC (Inversion of Control) container.

2-Life cycle details – includes its creation, initialization, usage, and destruction phases, managed by the IoC container.

3-Dependency management – involves injecting required values or dependencies into a bean during its creation.

Code Example

1- XML Ways – Github Project link – https://github.com/kuldeep101990/BeanHandlingSpringXml

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 way- Github project link – https://github.com/kuldeep101990/BeanHandlingSpringAnnotation

package beanHandlingSpringAnnotation;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
    // Properties of the bean
    private String name;
    private int age;
    // Default constructor
    public MyBean() {
        // Optional: You can initialize some default values
    }
    // Getter and setter methods for properties
    @Value("John")
    public void setName(String name) {
        this.name = name;
    }
    @Value("30")
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }
    // Initialization method using @PostConstruct
    @PostConstruct
    public void init() {
        System.out.println("Initializing MyBean...");
    }
    // Destruction method using @PreDestroy
    @PreDestroy
    public void cleanup() {
        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

Github Project Link (XML based) – https://github.com/kuldeep101990/BeanScopesSpringXml

Github Project Link (Annotation based) – https://github.com/kuldeep101990/BeanScopesSpringAnnotation

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)

Note – 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.

2- Step 11 & 12 are pre-destroy callback methods

Github Project link (XML based) – https://github.com/kuldeep101990/SpringBeanLifeCycleXml

Github Project link (Annotation based) – https://github.com/kuldeep101990/SpringBeanLifeCycleAnnotation

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

Github project link (XML based) – https://github.com/kuldeep101990/SpringBeanInheritanceXml

Github project link (Annotation based) – https://github.com/kuldeep101990/SpringBeanInheritanceAnnotation