1 实例化
当我们程序加载applicationContext.xml文件的时候(scope为singleton情况),把我们的bean实例化到内存中;默认使用无惨构造方法,初始化实例对象(所以一般都必须有一个无参构造方法);
2 调用setter方法设置属性
3 如果bean类实现了BeanNameAware接口,可以通过setBeanName方法获取bean的id号
public class UpperLetter implements BeanNameAware {
public void setBeanName(String arg0) {
System.out.println(
"setBeanName 方法调用 " + arg0);
}
}
4 如果bean类实现了BeanFactoryAware 接口,可以通过setBeanFactory方法获取BeanFactory
public class UpperLetter implements BeanFactoryAware {
public void setBeanFactory(BeanFactory arg0)
throws BeansException {
System.out.println(
"setBeanFactory 方法调用 " + arg0);
}
}
5 如果bean类实现了ApplicationContextAware接口,可以通过setApplicationContext方法获取ApplicationContext
public class UpperLetter implements ApplicationContextAware{
public void setApplicationContext(ApplicationContext arg0)
throws BeansException {
System.out.println(
"setApplicationContext 方法调用 " + arg0);
}
}
6 如果bean和一个后置处理器(BeanPostProcessor)关联,则会自动调用处理器的postProcessBeforeInitialization 方法
①记录每个对象,被实例化的时间 ②过滤每个调用对象ip ③给所有对象添加属性,或者函数==>aop(Aspect Oriented Programming面向切面编程,针对所有对象编程)
public class MyBeanPostProcessor implements BeanPostProcessor {
public Object
postProcessAfterInitialization(Object arg0, String arg1)
throws BeansException {
System.out.println(
"postProcessAfterInitialization 方法调用 " + arg0 +
" " + arg1 +
" " +
new Date());
return arg0;
}
public Object
postProcessBeforeInitialization(Object arg0, String arg1)
throws BeansException {
System.out.println(
"postProcessBeforeInitialization 方法调用 " + arg0 +
" " + arg1 +
" " +
new Date());
return arg0;
}
}
<bean id="myBeanPostProcessor" class="com.test.service.imp.MyBeanPostProcessor" />
7 如果bean类实现了InitializingBean接口,则会调用afterPropertiesSet方法
8 定制自己的init方法(在applicationContext.xml文件,init-method)
<bean id="changeLetter" init-method="init" class="com.test.service.imp.UpperLetter">
</bean>
public void init() {
System.
out.println(
"自己配置的init 方法调用 ");
}
9 调用处理器的postProcessAfterInitialization 方法
10 使用Bean对象,调用bean对象的方法
11 容器关闭
可以通过实现DisposableBean接口,调用destroy方法;也可以在applicationContext.xml文件中配置destroy-method,实现自己的myDestroy方法(常用自己配置的方法)
public class UpperLetter implements DisposableBean{
public void destroy()
throws Exception {
System.out.println(
"自己配置的init 方法调用 ");
}
}
<bean id="changeLetter" destroy-method="mydestroy" class="com.test.service.imp.UpperLetter">
</bean>
public void mydestroy() {
System.
out.println(
"自己配置的mydestroy 方法调用 ");
}
12 小结:一般使用到的流程是1->2->6->9->10->11