Spring_管理 Bean 的生命周期
beans-cycle.xml
<?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.xsd">
<bean id="car" class="com.hy.spring.beans.cycle.Car"
init-method="init"
destroy-method="destroy">
<property name="brand" value="AuDi"></property>
</bean>
</beans>
Car.java
package com.hy.spring.beans.cycle;
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 init(){
System.out.println("init.....");
}
public void destroy(){
System.out.println("destroy.....");
}
}
Main.java
package com.hy.spring.beans.cycle;
import org.springframework.context.ApplicationContext;
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(car);
//关闭IOC容器
ctx.close();
}
}
结果
xml 配置:
<!--
实现 BeanPostProcessor 接口,并具体提供
Object postProcessBeforeInitialization (Object bean, String beanName): init-method之前被调用
Object postProcessAfterInitialization (Object bean, String beanName): init-method之后被调用
的实现。
bean: bean实例本身。
beanName :IOC 容器配置的bean的名字。
返回值: 是实际上返回给用户的那个bean,注意:可以在以上两个方法中修改返回的bean,甚至返回一个新的bean
-->
<!-- 配置bean的后置处理器:不需要配置id,IOC容器自动识别是一个 BeanPostProcessor-->
<bean id="myBeanPostProcessor" class="com.hy.spring.beans.cycle.MyBeanPostProcessor">
</bean>
MyBeanPostProcessor.java
package com.hy.spring.beans.cycle;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class MyBeanPostProcessor implements BeanPostProcessor{
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("postProcessAfterInitialization:" + bean + ", " + beanName);
Car car = new Car();
car.setBrand("Ford");
return car;
}
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
if("car".equals(beanName)){
//....
}
System.out.println("postProcessBeforeInitialization:" + bean + ", " + beanName);
return bean;
}
}
Car.java
package com.hy.spring.beans.cycle;
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 init(){
System.out.println("init.....");
}
public void destroy(){
System.out.println("destroy.....");
}
@Override
public String toString() {
return "Car [brand=" + brand + "]";
}
}
结果: