模拟 Spring Bean 生命周期



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="car" class="com.spring.lief_cycle.Car"
          init-method="myInit"
          destroy-method="myDestroy" scope="singleton">
        <property name="brand" value="红旗CA72"></property>
        <property name="maxSpeed" value="100"></property>
    </bean>
</beans>



2016-11-02 17:25:54,952 DEBUG (DefaultSingletonBeanRegistry.java:215) - Creating shared instance of singleton bean 'car'
2016-11-02 17:25:54,954 DEBUG (AbstractAutowireCapableBeanFactory.java:435) - Creating instance of bean 'car'
InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation
===========>调用Car构造函数.
2016-11-02 17:25:54,978 DEBUG (AbstractAutowireCapableBeanFactory.java:509) - Eagerly caching bean 'car' to allow for resolving potential circular references
InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation
2016-11-02 17:25:54,990 DEBUG (SpringFactoriesLoader.java:75) - Loaded [org.springframework.beans.BeanInfoFactory] names: [org.springframework.beans.ExtendedBeanInfoFactory]
2016-11-02 17:25:54,994 DEBUG (CachedIntrospectionResults.java:231) - Getting BeanInfo for class [com.spring.lief_cycle.Car]
2016-11-02 17:25:55,003 DEBUG (CachedIntrospectionResults.java:259) - Caching PropertyDescriptors for class [com.spring.lief_cycle.Car]
2016-11-02 17:25:55,004 DEBUG (CachedIntrospectionResults.java:271) - Found bean property 'beanFactory' of type [org.springframework.beans.factory.BeanFactory]
2016-11-02 17:25:55,007 DEBUG (CachedIntrospectionResults.java:271) - Found bean property 'beanName' of type [java.lang.String]
2016-11-02 17:25:55,008 DEBUG (CachedIntrospectionResults.java:271) - Found bean property 'brand' of type [java.lang.String]
2016-11-02 17:25:55,011 DEBUG (CachedIntrospectionResults.java:271) - Found bean property 'class' of type [java.lang.Class]
2016-11-02 17:25:55,013 DEBUG (CachedIntrospectionResults.java:271) - Found bean property 'color' of type [java.lang.String]
2016-11-02 17:25:55,014 DEBUG (CachedIntrospectionResults.java:271) - Found bean property 'maxSpeed' of type [int]
InstantiationAwareBeanPostProcessor.postProcessPropertyValues
2016-11-02 17:25:55,048 DEBUG (AbstractEnvironment.java:112) - Initializing new StandardEnvironment
2016-11-02 17:25:55,051 DEBUG (MutablePropertySources.java:107) - Adding [systemProperties] PropertySource with lowest search precedence
2016-11-02 17:25:55,053 DEBUG (MutablePropertySources.java:107) - Adding [systemEnvironment] PropertySource with lowest search precedence
2016-11-02 17:25:55,055 DEBUG (AbstractEnvironment.java:116) - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
2016-11-02 17:25:55,058 DEBUG (AbstractEnvironment.java:112) - Initializing new StandardEnvironment
2016-11-02 17:25:55,060 DEBUG (MutablePropertySources.java:107) - Adding [systemProperties] PropertySource with lowest search precedence
2016-11-02 17:25:55,062 DEBUG (MutablePropertySources.java:107) - Adding [systemEnvironment] PropertySource with lowest search precedence
2016-11-02 17:25:55,064 DEBUG (AbstractEnvironment.java:116) - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
2016-11-02 17:25:55,068 DEBUG (AbstractEnvironment.java:112) - Initializing new StandardEnvironment
2016-11-02 17:25:55,070 DEBUG (MutablePropertySources.java:107) - Adding [systemProperties] PropertySource with lowest search precedence
2016-11-02 17:25:55,072 DEBUG (MutablePropertySources.java:107) - Adding [systemEnvironment] PropertySource with lowest search precedence
2016-11-02 17:25:55,074 DEBUG (AbstractEnvironment.java:116) - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
2016-11-02 17:25:55,080 DEBUG (AbstractEnvironment.java:112) - Initializing new StandardEnvironment
2016-11-02 17:25:55,082 DEBUG (MutablePropertySources.java:107) - Adding [systemProperties] PropertySource with lowest search precedence
2016-11-02 17:25:55,084 DEBUG (MutablePropertySources.java:107) - Adding [systemEnvironment] PropertySource with lowest search precedence
2016-11-02 17:25:55,086 DEBUG (AbstractEnvironment.java:116) - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
2016-11-02 17:25:55,091 DEBUG (AbstractEnvironment.java:112) - Initializing new StandardEnvironment
2016-11-02 17:25:55,093 DEBUG (MutablePropertySources.java:107) - Adding [systemProperties] PropertySource with lowest search precedence
2016-11-02 17:25:55,095 DEBUG (MutablePropertySources.java:107) - Adding [systemEnvironment] PropertySource with lowest search precedence
2016-11-02 17:25:55,098 DEBUG (AbstractEnvironment.java:116) - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
2016-11-02 17:25:55,108 DEBUG (TypeConverterDelegate.java:413) - Converting String to [int] using property editor [org.springframework.beans.propertyeditors.CustomNumberEditor@e425743]
设置Brand属性.
调用BeanNameAware.setBeanName()
调用BeanFactoryAware.setBeanFactory()
调用BeanPostProcessor.postProcessBeforeInitialization(),color为空,默认设置成黑色
2016-11-02 17:25:55,112 DEBUG (AbstractAutowireCapableBeanFactory.java:1529) - Invoking afterPropertiesSet() on bean with name 'car'
调用InitializingBean.afterPropertiesSet()
2016-11-02 17:25:55,113 DEBUG (AbstractAutowireCapableBeanFactory.java:1586) - Invoking init method  'myInit' on bean with name 'car'
调用init-method所指定的myInit(),将maxSpeed设置为240
调用BeanPostProcessor.postProcessAfterInitialization(),maxSpeed大于200 ,将maxSpeed调整为200
2016-11-02 17:25:55,119 DEBUG (AbstractAutowireCapableBeanFactory.java:463) - Finished creating instance of bean 'car'
brand:红旗CA72,color:黑色,maxSpeed:200
2016-11-02 17:26:09,581 DEBUG (AbstractBeanFactory.java:246) - Returning cached instance of singleton bean 'car'
car1==car2:true
2016-11-02 17:26:28,440 DEBUG (DisposableBeanAdapter.java:226) - Invoking destroy() on bean with name 'car'
调用DisposableBean.destroy()
2016-11-02 17:26:28,442 DEBUG (DisposableBeanAdapter.java:302) - Invoking destroy method 'myDestroy' on bean with name 'car'
调用destroy-method所指定的myDestroy()
Disconnected from the target VM, address: '127.0.0.1:6638', transport: 'socket'

Process finished with exit code 0





public class BeanLifeCycle {
    private static void LifeCycleInBeanFactory() {
        //装在配置文件并启动容器
        Resource res = new ClassPathResource("config/lief_cycle/beans.xml");
        BeanFactory bf = new XmlBeanFactory(res);

        //向容器中注册MyBeanPostProcessor后处理器
        ((ConfigurableBeanFactory) bf).addBeanPostProcessor(new MyBeanPostProcessor());
        //向容器中注册MyInstantiationAwareBeanPostProcessor后处理器
        ((ConfigurableBeanFactory) bf).addBeanPostProcessor(new MyInstantiationAwareBeanPostProcessor());
        //第一次从容器中获取car,将触发容器实例化该Bean,这将引发Bean生命周期方法的调用
        Car car1 = (Car) bf.getBean("car");
        car1.introduce();
        car1.setColor("红色");


        //第二次从容器中获取car,是从缓存池中取得的
        Car car2 = (Car) bf.getBean("car");
       System.out.println("car1==car2:"+(car1==car2));

        //关闭容器
        ((XmlBeanFactory)bf).destroySingleton("car");
    }

    public static void main(String args[]){
        LifeCycleInBeanFactory();
    }


}


public class MyBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if(beanName.equals("car")){
            Car car  = (Car) bean ;
            if(car.getColor()==null){
                System.out.println("调用BeanPostProcessor.postProcessBeforeInitialization(),color为空,默认设置成黑色");
                car.setColor("黑色");
            }
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if(beanName.equals("car")){
            Car car  = (Car) bean ;
            if(car.getMaxSpeed()>200){
                System.out.println("调用BeanPostProcessor.postProcessAfterInitialization(),maxSpeed大于200 ,将maxSpeed调整为200");
                car.setMaxSpeed(200);
            }
        }
        return bean;
    }
}

public class MyInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter {


    //接口方法:在实例化Bean前进行调用
    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        if ("car".equals(beanName)) {
            System.out.println("InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation");
        }
        return null;
    }

    //接口方法:在实例化Bean后进行调用
    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        if ("car".equals(beanName)) {
            System.out.println("InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation");
        }
        return true;
    }

    //接口方法,在设置某个属性时调用
    @Override
    public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
        //仅对容器中Car Bean进行处理,还可以通过post入参进行过滤。
        //仅对car的某个特定属性进行处理
        if ("car".equals(beanName)) {
            System.out.println("InstantiationAwareBeanPostProcessor.postProcessPropertyValues");
        }
        return pvs;
    }
}





public class Car implements BeanFactoryAware, BeanNameAware, InitializingBean, DisposableBean {

//    private > default > protected > public

    private String brand;
    private String color;
    private int maxSpeed;

    private BeanFactory beanFactory;
    private String beanName;

    public Car() {
        System.out.println("===========>调用Car构造函数.");
    }


    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        System.out.println("设置Brand属性.");
        this.brand = brand;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public int getMaxSpeed() {
        return maxSpeed;
    }

    public void setMaxSpeed(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }

    public void introduce() {
        System.out.println("brand:" + brand + ",color:" + color + ",maxSpeed:" + maxSpeed);
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("调用BeanFactoryAware.setBeanFactory()");
        this.beanFactory = beanFactory;
    }

    @Override
    public void setBeanName(String beanName) {
        System.out.println("调用BeanNameAware.setBeanName()");
        this.beanName = beanName;
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("调用DisposableBean.destroy()");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("调用InitializingBean.afterPropertiesSet()");
    }

    public void myInit() {
        System.out.println("调用init-method所指定的myInit(),将maxSpeed设置为240");
        this.maxSpeed = 240;
    }

    public void myDestroy() {
        System.out.println("调用destroy-method所指定的myDestroy()");
    }

}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值