SpringBoot的Bean的生命周期
目录
1.实例化Bean对象
Bean的实例化是在BeanFactory中完成的。BeanFactory通过调用Bean的构造函数来创建Bean的实例,此时还未进行任何属性注入。
源码:
//从beanDefinition中获取Bean的class
Class<?> beanClass = resolveBeanClass(beanDefinition, beanName);
//根据构造函数实例化Bean对象
Object beanInstance = createBeanInstance(beanName, beanDefinition, args);
实例代码:
// 使用容器
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
没有整合SpringBoot之前:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
//读取配置文件并实例化Bean
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
Object bean = context.getBean("beanId");
2.处理Bean的属性依赖
在实例化Bean对象之后,Spring容器会将按照实例化时配置的属性进行依赖注入,也就是将其他的Bean对象注入进来,这一步也是整个生命周期中比较重要的一步。
populateBean(beanName, beanDefinition, instanceWrapper);
例如:
@Component("userService")
public class UserServiceImpl implements BeanNameAware, UserService {
@Autowied
private OrderService orderService;
}
UserServiceImpl 需要依赖OrderService ,因此在UserServiceImpl 实例化之后,Spring容器会自动将OrderService 对象注入进来。
源码:
3.Bean的初始化
初始化是在BeanFactory中完成的,包括调用InitializingBean
的afterPropertiesSet()
方法或@PostConstruct
注解标注的方法等。
if (mbd.getInitMethodName() != null || mbd.getDestroyMethodName() != null) {
return createLifecycleProcessor().initializeBean(beanName, exposedObject, mbd);
}
3.1 前置处理
如果Bean实现了BeanPostProcessor接口,则在Bean的初始化之前调用postProcessBeforeInitialization()方法。这是BeanPostProcessor的前置处理,可以对Bean进行任何必要的修改。
3.2 后置处理
如果Bean实现了BeanPostProcessor接口,则在Bean的初始化之后调用postProcessAfterInitialization()方法。这是BeanPostProcessor的后置处理,可以对Bean进行任何必要的修改。
4.Bean在容器中的使用
Bean在容器中的使用包括:getBean
或@Autowire
注解等。当容器使用某个Bean时,Bean实例已经存在并且初始化完毕。
5.Bean的销毁
Bean的销毁可以通过实现DisposableBean
接口的其中一个方法destroy()
实现,也可以通过@PreDestroy
注解标注的方法实现。由于Spring的IoC容器是单例模式的,所以在容器的销毁过程中会调用单例Bean的销毁方法。
源码:
if (mbd.getDestroyMethodName() != null) {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
小结:
较为重要的在2、3步。