Bean Life Cycle in Spring Framwork

Good Evening Folks.

Every Java developer knows that at the time of creation of any object if some initialization is required we keep in constructor.
Example.

When it comes to J2EE Technology like Servlet we can do same initialization work in init() method.

But when it comes to Spring bean question comes in mind spring bean is nothing but simple java class with some properties.
Example.

Can is put the initialization stuff inside Constructor ? how to initialize a bean because a bean is something related to Spring IOC container.Since spring bean is not servlet there is no init method and i can’t put the initialization logic in Constructor as Spring bean life cycle is managed by Spring IOC container.

Solution
Since Spring bean and its lifeCycle is managed by Spring IOC Container thats where spring people came up with approach Bean LifeCycle. Now we can write the initialization logic.
There are 2 approches by using we can achieve this task.

1.Declarative Approach.
2.Programmatic Approach

Lets see One by One.

1.Declarative Approach.

Lets take an example to understand it.

In this example suppose i am creating bean by providing one value of property ‘a’ via constructor injection, and property ‘b’ via setter injection and but here is problem i need the value of sum also nothing but some initialization process [sum of a+b to create complete the Bean].

we will create 2 methods named init and destroy and configure them in configuration file as folows.
We can achieve this via Declarative approach.
Bean-configuration

Here Spring IOC container will first inject value of propeerty ‘a’ via Constructor injection then value of property ‘b’ will be injected via setter injection after all injections has been performed IOC Container call init method that’s where initialization logic gets executed and a bean will be created with all values.

2.Programmatic Approach
Where In Programmatic Approach bean needs need to implement spring provided interfaces InitializingBean,DisposableBean
Example

Spring IOC Container will take care of bean lifecycle

Hope This helps. Feel free to comment

To view or add a comment, sign in

Others also viewed

Explore content categories