xml配置
<bean id = "car" class="cycle.Car" init-method="init">
<property name="brand" value="bmw"></property>
</bean>
<!--
BeanPostProcessor接口
实现初始化前后的两个方法postProcessAfterInitialization postProcessBeforeInitialization
bean是返回的实例
beanname是ioc容器配置bean的
-->
<bean class="cycle.MyBeanProcessor"></bean>
实现BeanPostProcessor接口
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class MyBeanProcessor implements BeanPostProcessor{
@Override
public Object postProcessAfterInitialization(Object bean, String beanname)
throws BeansException {
// TODO Auto-generated method stub
System.out.println("afterinit");
return bean;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanname)
throws BeansException {
// TODO Auto-generated method stub
System.out.println("beforeinit");
return bean;
}
}
生命周期代码
ApplicationContext c = new ClassPathXmlApplicationContext("bean-cycle.xml");
Car car = (Car) c.getBean("car2");
System.out.println(car);
结果
construction
注入属性
beforeinit
init....
afterinit
Car [brand=bmw]
IOC容器创建bean实例-->属性注入-->初始化前置方法执行-->进行初始化-->初始化后置方法执行-->获得实例bean
实体类
package cycle;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Car {
String brand;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
System.out.println("注入属性");
this.brand = brand;
}
@Override
public String toString() {
return "Car [brand=" + brand + "]";
}
public Car(String brand) {
super();
this.brand = brand;
}
public Car() {
// super();
System.out.println("construction");
}
public void init(){
System.out.println("init....");
}
public static void main(String[] args) {
ApplicationContext c = new ClassPathXmlApplicationContext("bean-cycle.xml");
Car car = (Car) c.getBean("car");
System.out.println(car);
}
}
网友评论