I am yet to find a high-level definition of Spring beans that I can understand. I see them referenced often in Grails documentation and books, but I think that understanding what they are would be beneficial. So what are Spring beans? How can they be used? Do they have something to do with Dependency Injection?
12 Answers
First let us understand Spring:
Spring is a lightweight and flexible framework.
Analogy:
Java Beans are classes that encapsulate many objects into a single object (the bean). The name “Bean” was given to encompass this standard, which aims to create reusable software components for Java.
Spring Bean: is an object, which is created, managed and destroyed in Spring Container. We can inject an object into the Spring Container through the metadata(either xml or annotation), which is called inversion of control.
Analogy:
Let us assume farmer is having a farmland cultivating by seeds(or beans).
Here, Farmer is Spring Framework, Farmland land is Spring Container, Beans are Spring Beans, Cultivating is Spring Processors.
Like bean life-cycle, spring beans too having it’s own life-cycle.
img source
Following is sequence of a bean lifecycle in Spring:
-
Instantiate: First the spring container finds the bean’s definition from the XML file and instantiates the bean.
-
Populate properties: Using the dependency injection, spring populates all of the properties as specified in the bean definition.
-
Set Bean Name: If the bean implements
BeanNameAware
interface, spring passes the bean’s id tosetBeanName()
method. -
Set Bean factory: If Bean implements
BeanFactoryAware
interface, spring passes the beanfactory tosetBeanFactory()
method. -
Pre-Initialization: Also called post process of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls
postProcesserBeforeInitialization()
method. -
Initialize beans: If the bean implements
IntializingBean
,itsafterPropertySet()
method is called. If the bean has init method declaration, the specified initialization method is called. -
Post-Initialization: – If there are any
BeanPostProcessors
associated with the bean, theirpostProcessAfterInitialization()
methods will be called. -
Ready to use: Now the bean is ready to use by the application
-
Destroy: If the bean implements
DisposableBean
, it will call thedestroy()
method