1.通过构造器或者工厂方法创建bean的实例
2.为bean的属性设置值和对其他bean的引用
3.将bean的实例传递给bean的后置处理器BeanPostProcessor的postProcessBeforeInitialization方法
4.调用bean的初始化方法
5.调用bean的后置处理器BeanPostProcessor的postProcessAfterInitialization方法
6.使用bean容器
7.调用bean的销毁方法
创建Car类 定义以下方法
public class Car { public Car() { System.out.println("create car"); } private String brand; public void setBrand(String brand) { System.out.println("set brand"); this.brand = brand; } public void init() { System.out.println("init ..."); } public void destroy() { System.out.println("destroy..."); } @Override public String toString() { return "Car [brand=" + brand + "]"; } }
创建一个类实现BeanPostProcessor接口 重写两个方法
public class MyBeanPostProcessor implements BeanPostProcessor{ @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { // TODO Auto-generated method stub System.out.println("postProcessBeforeInitialization"+bean+","+beanName); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { // TODO Auto-generated method stub System.out.println("postProcessAfterInitialization"+bean+","+beanName); return bean; } }
在applicationContext.xml中配置bean
<bean id="car" class="beancycle.Car" init-method="init" destroy-method="destroy"> <property name="brand" value="aodi"></property> </bean> <bean class="beancycle.MyBeanPostProcessor"></bean>
编写main方法测试
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Car car = (Car)context.getBean("car"); car.destroy(); }
输出结果如下
create car
set brand
postProcessBeforeInitializationCar [brand=aodi],car
init ...
postProcessAfterInitializationCar [brand=aodi],car
destroy...