(七)SpringIOC容器中bean生命周期

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fangxinde/article/details/78289342

SpringIOC容器可以管理Bean的生命周期Spring允许在Bean生命周期的特定点执行定制任务。
SpringIOC容器对Bean的生命周期进行管理的过程:
1.通过构造器或工厂方法创建Bean实例
2.为Bean的属性设置值和对其他Bean的引用
3.调用Bean的初始化方法
4.Bean可以使用了
5.当容器关闭时,调用Bean 的销毁方法
第一步:配置xml文件
<这里写代码片?xml version=”1.0” encoding=”UTF-8”?>

package com.atguigu.spring.beans.cycle;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class MyBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object  bean, String beanName)
            throws BeansException {
        //postProcess是处理所有bean的所以处理时要进行过滤
        System.out.println("postProcessBeforeInitialization:"+bean+","+beanName);
        //Car car=new Car();
        //if("car".equals(beanName)){   
        //car.setBrand("ford"); 
        //}
        return bean;
    }
    //初始化之后执行该方法
        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName)
                throws BeansException {
            System.out.println("postProcessAfterInitialization:"+bean+","+beanName);
            Car car=new Car();
            car.setBrand("ford");
            return car;
        }

}

第三步:新建bean类

public class Car {
    public Car(){
        System.out.println("Car's Constructor....");
    }
    private String brand;
    public void setBrand(String brand){
        System.out.println("setBrand...");
        this.brand=brand;
    }
    public void init2(){
        System.out.println("init.....");
    }
    public void destroy(){
        System.out.println("destroy.....");
    }
    @Override
    public String toString() {
        return "Car [brand=" + brand + "]";
    }

}

第四步:执行main方法

package com.atguigu.spring.beans.cycle;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("beans-cycle.xml");
        Car car=(Car) ctx.getBean("car");
        System.out.println("tostring:"+car);
        //关闭IOC容器
        ctx.close();        
    }
}

猜你喜欢

转载自blog.csdn.net/fangxinde/article/details/78289342