What in the world are Spring beans?

前端 未结 12 1451
谎友^
谎友^ 2020-11-28 00:19

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

12条回答
  •  时光取名叫无心
    2020-11-28 00:44

    First let us understand Spring:

    Spring is a lightweight and flexible framework.

    Analogy:

    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 to setBeanName() method.

    • Set Bean factory: If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() 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,its afterPropertySet() 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, their postProcessAfterInitialization() 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 the destroy() method

提交回复
热议问题