1 package SpringBeansCycle; 2 3 public class Car { 4 private String brand; 5 6 public Car() { 7 System.out.println("我是一个构造器"); 8 } 9 10 public void init() { 11 System.out.println("this is a init!"); 12 } 13 14 public void destory() { 15 System.out.println("this is a destory!"); 16 } 17 18 public String getBrand() { 19 return brand; 20 } 21 22 public void setBrand(String brand) { 23 this.brand = brand; 24 } 25 26 }
1 package SpringBeansCycle; 2 3 import org.springframework.beans.BeansException; 4 import org.springframework.beans.factory.config.BeanPostProcessor; 5 6 public class MyBeanPostProcesser implements BeanPostProcessor { 7 8 @Override 9 public Object postProcessBeforeInitialization(Object o, String s) throws BeansException { 10 System.out.println(s); 11 return o; 12 } 13 14 @Override 15 public Object postProcessAfterInitialization(Object o, String s) throws BeansException { 16 System.out.println("postProcessAfterInitialization"); 17 return o; 18 } 19 }
1 package SpringBeansCycle; 2 3 import org.springframework.context.support.ClassPathXmlApplicationContext; 4 5 public class Main { 6 public static void main(String[] args) { 7 ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("SpringBeansCycle/beans-cycle.xml"); 8 Car car = (Car) ctx.getBean("car"); 9 System.out.println(car); 10 //关闭IOC容器 11 ctx.close(); 12 } 13 }
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 5 <!--定义一个类实现BeanPostProcessor类之后可以在配置文件中,配置只有class的bean然后在调用实例类的初始化方法的时候,会对该类进行前后的调用--> 6 <bean id="car" class="SpringBeansCycle.Car" 7 init-method="init" destroy-method="destory"> 8 <property name="brand" value="#{'宝马'}"></property> 9 </bean> 10 <bean class="SpringBeansCycle.MyBeanPostProcesser"></bean> 11 12 </beans>