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...

转载于:https://www.cnblogs.com/helloDuo/p/9749473.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值