什么是Bean
在Spring中,由Spring IoC容器管理的构成应用程序主干的对象称为bean。bean是由Spring IoC容器实例化、组装和管理的对象。否则,bean只是应用程序中的众多对象之一。bean及其之间的依赖关系反映在容器使用的配置元数据中,通俗来讲Bean就是我们写的Java类。
普通对象(Bean)的生命周期
- 实例化
- 该对象不再被使用时通过垃圾回收机制进行回收
public static void main(String[] args) {
// 1.实例化
User user = new User();
// 2、使用对象
user.setName("toString");
user.getName();
// 3.user对象不再使用就会被JVM回收
user = null;
}
Spring Bean初始化的流程
1、实例化 Instantiation // 调用构造器创建对象
2、属性赋值 Populate // 依赖注入(controller中要注入service)
3、初始化 Initialization // Spring初始化的方法,init
4、销毁 Destruction // 容器关闭
// AbstractAutowireCapableBeanFactory.java
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// 1.实例化
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
// Initialize the bean instance.
try {
// 2.赋值(DI)
populateBean(beanName, mbd, instanceWrapper);
// 3.初始化
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
return exposedObject;
}
容器关闭时调用ConfigurableApplicationContext#close()销毁对象
public void close() {
synchronized (this.startupShutdownMonitor) {
doClose();
if (this.shutdownHook != null) {
try {
Runtime.getRuntime().removeShutdownHook(this.shutdownHook);
}
catch (IllegalStateException ex) {
// ignore - VM is already shutting down
}
}
}
}
SpringBean生命周期函数分类
Bean自身的方法
这个包