通过上面的步骤我们发现,Spring实例一个bean时,这个bean是在不断的变化的
为了更好的说明以上步骤,请看下面代码:
实体类:
package com.lx.test;上下文工具类
package com.lx.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Bean上下文工具类
*/
public class BeanContextHelper {
private static ApplicationContext _instance;
static {
if (_instance == null)
_instance = buildApplicationContext();
}
private BeanContextHelper() {
}
/**
* 重新构建ApplicationContext对象
*/
public static ApplicationContext buildApplicationContext() {
return new ClassPathXmlApplicationContext("applicationContext-base.xml");
}
/**
* 获取一个ApplicationContext对象
*/
public static ApplicationContext getApplicationContext() {
return _instance;
}
}
测试类
package com.lx.test;
import org.springframework.context.ApplicationContext;
/**
* BeanFactory实例化Bean工程测试类
*/
public class Test {
public static void main(String args[]) {
Test test = new Test();
test.test();
}
public void test() {
ApplicationContext context = BeanContextHelper.getApplicationContext();
Employee employee = (Employee) context.getBean("employee");
System.out.println("**********从Spring BeanFactory获取到的最终bean实例**********");
System.out.println("最终bean的值:" + employee);
}
}
执行后的结果
信息: Loading XML bean definitions from class path resource [applicationContext-base.xml]
**********第一步:调用Bean的默认构造方法**********
bean1的 值:Employee [id=bean1:G080405214, name=ZHANGSAN, sex=null, age=null, nativePlace=null, department=null, beanName=null]
**********第二步:检查Bean配置文件中是否注入了Bean的属性值**********
bean1的 值:957932937
**********设置bean的名称**********
bean2的值:Employee [id=bean1:G080405214, name=ZHANGSAN, sex=null, age=null, nativePlace=null, department=bean2:研发部, beanName=myBeanName]
**********第三步:检查Bean是否实现了InitializingBean接口**********
bean3的值:Employee [id=bean1:G080405214, name=bean3:李晓红, sex=bean3:女, age=bean3:25, nativePlace=null, department=bean2:研发部, beanName=myBeanName]
**********第四步:检查Bean配置文件中是否指定了init-method此属性**********
bean4的值:Employee [id=bean1:G080405214, name=bean3:李晓红, sex=bean3:女, age=bean3:25, nativePlace=bean3:北京, department=bean2:研发部, beanName=myBeanName]
**********从Spring BeanFactory获取到的最终bean实例**********
最终bean的值:Employee [id=bean1:G080405214, name=bean3:李晓红, sex=bean3:女, age=bean3:25, nativePlace=bean3:北京, department=bean2:研发部, beanName=myBeanName]
Employee实现了3个接口:
InitializingBean:此接口提供afterPropertiesSet()方法,它的作用是为bean提供了定义初始化的功能。
DisposableBean:此接口提供destroy()方法,它的作用是在bean实例销毁前提供操作的功能。
BeanNameAware:此接口提供setBeanName()方法,它的作用是提供设置bean名称的功能,从上面的运行结果可以看出,此方法是在第二步进行的。