Spring IOC容器对bean的生命周期进行管理的过程

1.通过构造器或者工厂方法创建bean的实例

2.为bean的属性设置值和对其他bean的引用

3.将bean的实例传递给bean的后置处理器BeanPostProcessor的postProcessBeforeInitialization方法

4.调用bean的初始化方法

5.调用bean的后置处理器BeanPostProcessor的postProcessAfterInitialization方法

6.使用bean容器

7.调用bean的销毁方法

创建Car类 定义以下方法

 1 public class Car {
 2 
 3     public Car() {
 4         System.out.println("create car");
 5     }
 6     
 7     private String brand;
 8     
 9     public void setBrand(String brand) {
10         System.out.println("set brand");
11         this.brand = brand;    
12     }
13     
14     public void init() {
15         System.out.println("init ...");
16     }
17     
18     public void destroy() {
19         System.out.println("destroy...");
20     }
21 
22     @Override
23     public String toString() {
24         return "Car [brand=" + brand + "]";
25     }
26     
27 }
View Code

创建一个类实现BeanPostProcessor接口  重写两个方法

 1 public class MyBeanPostProcessor implements BeanPostProcessor{
 2 
 3     @Override
 4     public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
 5         // TODO Auto-generated method stub
 6         System.out.println("postProcessBeforeInitialization"+bean+","+beanName);
 7         return bean;
 8     }
 9     
10     @Override
11     public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
12         // TODO Auto-generated method stub
13         System.out.println("postProcessAfterInitialization"+bean+","+beanName);
14         return bean;
15     }
16 
17 }
View Code

在applicationContext.xml中配置bean

1 <bean id="car" class="beancycle.Car" 
2       init-method="init" destroy-method="destroy">
3           <property name="brand" value="aodi"></property>
4       </bean>
5       
6       <bean class="beancycle.MyBeanPostProcessor"></bean>
View Code

编写main方法测试

1 public static void main(String[] args) {
2         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
3         Car car = (Car)context.getBean("car");
4         car.destroy();
5         
6     }
View Code

输出结果如下

create car
set brand
postProcessBeforeInitializationCar [brand=aodi],car
init ...
postProcessAfterInitializationCar [brand=aodi],car
destroy...

猜你喜欢

转载自www.cnblogs.com/helloDuo/p/9749473.html