1、什么是Bean

In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application

Bean就是由IOC实例化、组装、管理的一个对象。

2、Bean的生命周期

**2.1、**在这里我们的Bean的生命周期主要指的是singleton bean,对prototype bean来说,当用户getBean获得prototype bean的实例后,IOC容器就不再对当前实例进行管理,而是把管理权交由用户,此后再getBean生成的是新的实例。此外还有(request/session/application/websocket)暂且不谈

<aside> 📖 在不同的容器中,Bean的生命周期开始的时间不同:

ApplicationContext:当容器启动的时候,bean就已经实例化

BeanFactory:直到调用getBean()方法的时候才进行实例化

普通的Java对象:生命周期: 实例化—>不再使用的时候通过垃圾回收机制进行回收

</aside>

Untitled

<aside> 💡 Bean自身的方法和Bean级生命周期方法都只对当前Bean起作用,但是容器级生命周期方法和工厂后处理器方法是对所有的bean都起作用

</aside>

**2.3、**其中:BeanPostProcessor和BeanFactoryPostProcessor就是Spring创建的扩展点,用户可以创建自己的实现类来修改Bean或者BeanFactory

ApplicatonContext:容器可以自动检测并加载BeanPostProcessor和BeanFactoryPostProcessor;

**BeanFactory:**需要自己调用方法手动注册。

BeanPostProcessor和BeanFactoryPostProcessor都可以有多个。ApplicationContext也可以根据org.springframework.core.PriorityOrdered和org.springframework.core.Ordered来进行自定义排序,但是BeanFactory不可以,默认顺序就是注册顺序。

注意:

3、常用接口说明

  1. BeanNameAware:该接口只有一个方法setBeanName(String name),用来获取bean的id或者name;