Spring笔记三:bean生命周期

创建bean后置处理器:
bean后置处理器允许在调用初始化方法前后对bean进行额外的处理。
它对所有的bean实例进行逐一处理,而非单一实例。
典型应用:检查bean属性的正确性或根据特定的标准更改bean的属性。

容器对bean生命周期管理:

  1. 创建bean实例
  2. 为bean的属性设置值或引用其它bean
  3. 将bean实例传递给实现了BeanPostProcessor接口的后置处理postProcessBeforeInitialization方法
  4. 调用bean的初始化方法
  5. 将bean实例传递给实现了BeanPostProcessor接口的后置处理postProcessAfterInitialization方法
  6. bean使用
  7. 容器关闭时,调用bean的销毁方法

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

    <bean id="car" class="com.spring.cycle.Car" init-method="init" destroy-method="destroy">
        <property name="brand" value="Audi">property>
    bean>
    
    
    <bean class="com.spring.cycle.BeanPostProcessor">bean>
beans>

“`
public class BeanPostProcessor implements org.springframework.beans.factory.config.BeanPostProcessor{
@Override
public Object postProcessBeforeInitialization(Object bean, String beanname) throws BeansException {
System.out.println(“postProcessBeforeInitialization “+bean+beanname);
return bean;
}

@Override
public Object postProcessAfterInitialization(Object bean, String beanname) throws BeansException {
    System.out.println("postProcessAfterInitialization  "+bean+beanname);
    return bean;
}

}

constructor...
setBrand...
postProcessBeforeInitialization Car{brand='Audi'}car
initing...
postProcessAfterInitialization Car{brand='Audi'}car
org.springframework.context.support.ClassPathXmlApplicationContext doClose
信息Closing org.springframework.context.support.ClassPathXmlApplicationContext@8c4c35: startup date [Wed Aug 22 09:43:00 CST 2018]; root of context hierarchy
Car{brand='Audi'}
destroying...

你可能感兴趣的:(Java框架学习Spring篇)