Bean的生命周期可以理解为以下几个步骤:
一、bean的定义
bean的定义一般是由我们开发者来完成的,第一种方法是在spring主配置文件中定义一个bean
<bean id="stu" class="com.apesource.jopo.student">
<property name="sname" value="鲁智深"/>
<property name="sage" value=17/>
</bean>
第二种是用注解直接注入
@Component
public class Stu{
private String sname;
private int sage;
}
第三种是在配置类中使用@Bean
二、bean的实例化
Bean已经定义好了,在spring启动时就会将定义好的Bean进行注册,然后调用了refresh()方法
//源码
public void refresh() throws BeansException, IllegalStateException {
synchronized(this.startupShutdownMonitor) {
this.prepareRefresh();
//用来解析配置文件,知道那些Bean需要被创建
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
this.prepareBeanFactory(beanFactory);
try {
this.postProcessBeanFactory(beanFactory);