Bean的生命周期
1. 由BeanFactory读取Bean定义文件,并生成各个Bean实例
2. 使用依赖注入,Spring按照Bean定义的信息中配置的所有的属性值,包括bean中bean属性。
3. 如果Bean实现了BeanNameAware接口,工厂调用Bean的setBeanName()方法传递的id
4. 如果Bean实现了BeanFactoryAware接口,工程调用setBeanFactory()方法传入工厂自身。
5. 如果有BeanPostProcessor和Bean关联,那么其postProcessBeforeInitalization()方法将被调用。
6. 如果Bean指定了Init-method方法被调用
7. 最后,如果有BeanPostProcessor和Bean关联,那么其postProcessAfterInitalization()方法将被调用。
此时的Bean已经可以被应用系统使用,并将被保留在BeanFactory中知道它不在被需要可以将其从BeanFactory中删除。
如果Bean实现了disposableBean接口,destroy()方法被调用
BeanNameAware中的setBeanName()方法设置bean的名字此时得到的名字是xml文件中的配置的id属性。
例:
applicationContext.xml 配置
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<beanid="studentDaoImpl"class="com.csdn.dao.StudentDaoImpl"scope="singleton">
</bean>
<beanid="studentServiceImpl"class="com.csdn.service.StudentServiceImpl"scope="singleton">
</bean>
</beans>
StudentServiceImpl中
public class StudentServiceImpl implements StudentService, BeanNameAware { @Override
publicvoidsetBeanName(String arg0) {
System.out.println(arg0);
}
}
此时的输出结果是:
studentServiceImpl
完整案例
StudentServiceImpl中
publicclass StudentServiceImpl implementsStudentService,BeanNameAware,BeanFactoryAware, BeanPostProcessor {
publicvoidinit() {
System.out.println("调用初始化的方法");
}
@Override
publicvoid insert() {
sd.insert();
}
@Override
publicvoidsetBeanName(String arg0) {
System.out.println("调用setBeanName其值为" + arg0);
}
@Override
publicvoidsetBeanFactory(BeanFactoryarg0) throwsBeansException {
System.out.println("调用setBeanFactory()");
}
@Override
publicObjectpostProcessAfterInitialization(Object arg0, String arg1)
throwsBeansException {
System.out.println("调用postProcessAfterInitialization");
returnarg0;
}
@Override
public Object postProcessBeforeInitialization(Object arg0, String arg1)
throwsBeansException {
System.out.println("调用postProcessBeforeInitialization");
returnarg0;
}
}
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<beanid="studentDaoImpl"class="com.csdn.dao.StudentDaoImpl"scope="singleton"init-method="init">
</bean>
<beanid="studentServiceImpl"class="com.csdn.service.StudentServiceImpl"scope="singleton">
</bean>
</beans>
输出的结果是
调用setBeanName其值为studentServiceImpl
调用setBeanFactory()
调用postProcessBeforeInitialization
调用初始化的方法
调用postProcessAfterInitialization