Spring IOC容器管理bean的生命周期:
例:
实体类Car.java里有--
// 自己定义初始化和销毁的方法体
public void init(){
System.out.println("init...");
}
public void destroy(){
System.out.println("destroy...");
}
配置bean:
<bean id="car" class="com.spring.beans.circle.Car"
p:brand="aodi" init-method="init" destroy-method="destroy"></bean>
测试:
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans-circle.xml");
Car car = (Car) ctx.getBean("car");
System.out.println(car);
ctx.close();
bean的后置处理器:
bean后置处理器是为了在bean的初始化前后对bean进行额外的处理。
例:
1、先写一个MyBeanPostProcessor.java
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
// 使用BeanPostProcessor接口
public class MyBeanPostProcessor implements BeanPostProcessor{
@Override
public Object postProcessAfterInitialization(Object arg0, String arg1) throws BeansException {
// TODO Auto-generated method stub
System.out.println("postProcessAfterInitialization:"+arg0+" , "+arg1);
return arg0;
}
@Override
public Object postProcessBeforeInitialization(Object arg0, String arg1) throws BeansException {
// TODO Auto-generated method stub
System.out.println("postProcessBeforeInitialization:"+arg0+" , "+arg1);
return arg0;
}
}
备注:该类就是用来处理所有bean的类,其中方法的参数arg0代表bean的类的对象,参数arg1代表beanname
2、配置文件
<bean id="car" class="com.spring.beans.circle.Car"
p:brand="aodi" init-method="init" destroy-method="destroy"></bean>
<!-- 配置bean的后置处理器 -->
<bean class="com.spring.beans.circle.MyBeanPostProcessor"></bean>
3、Main.java
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans-circle.xml");
Car car = (Car) ctx.getBean("car");
//System.out.println(car);
ctx.close();
4、执行结果:
构造car
postProcessBeforeInitialization:com.spring.beans.circle.Car@42d80b78 , car
init...
postProcessAfterInitialization:com.spring.beans.circle.Car@42d80b78 , car
destroy...