1.生命周期
从对象创建到对象销毁的过程。
2.bean的生命周期
- 通过构造器创建bean实例(无参数构造器)
- 为bean的属性设置值和对其他bean的引用(调用set方法)
- 调用bean的初始化方法方法(需要配置初始化方法)
- bean可以使用
- IOC容器关闭时,调用bean的销毁方法(配置销毁方法)
Java类
public class Order {
public Order() {
System.out.println("第一步 执行无参构造器创建bean实例");
}
private String name;
public void setName(String name) {
this.name = name;
System.out.println("第二步 调用set方法设置属性");
}
public void initMethod(){
System.out.println("第三部 执行初始化方法");
}
public void desodryMethod(){
System.out.println("第五步 执行销毁方法");
}
}
bean,xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:util="http://www.springframework.org/schema/util"
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
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-beans.xsd">
<bean name="order" class="com.cap.cycle.Order" init-method="initMethod" destroy-method="desodryMethod">
<property name="name" value="订单"></property>
</bean>
</beans>
test
public class test {
@Test
public void testService(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml");
Order order = context.getBean("order", Order.class);
System.out.println("第四步 获取bean实例"+order);
context.close();
}
}
3.加上后置处理器后,一共有七步
- 通过构造器创建bean实例(无参数构造器)
- 为bean的属性设置值和对其他bean的引用(调用set方法)
- 把bean实例传递给bean后置处理器的方法--postProcessBeforeInitialization
- 调用bean的初始化方法方法(需要配置初始化方法)
- 把bean实例传递给bean后置处理器的方法--postProcessAfterInitialization
- bean可以使用
- IOC容器关闭时,调用bean的销毁方法(配置销毁方法)
4.实现BeanPostProcessor接口,Override两个方法
public class MyPostBean implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("第三步 后置处理器before方法");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("第五步 后置处理器after方法");
return bean;
}
}
xml配置文件,配置了后置处理器。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:util="http://www.springframework.org/schema/util"
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
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-beans.xsd">
<bean name="order" class="com.cap.cycle.Order" init-method="initMethod" destroy-method="desodryMethod">
<property name="name" value="订单"></property>
</bean>
<!--xml文件中配置后置处理器,配置后所有的bean都会添加调用里面配置的方法-->
<bean name="myPostBean" class="com.cap.cycle.MyPostBean"></bean>
</beans>