- 通过构造器创建实例
- 为Bean的属性设置值。(调用Set方法)
- 调用Bean初始化的方法(需要自己配置)
- 对象可以使用(获取对象)
- 当容器关闭是,调用bean的销毁的方法(需要自己配置)
实例验证,通过在相应方法中设置输出。
创建类并为对应方法设置输出
public class Time {
//构造方法
public Time() {
System.out.println("The first step");
}
private String time;
public void setTime(String time) {
this.time = time;
System.out.println("The second:为Bean注入属性");
}
//初始化方法,需要配置
public void initMethod(){
System.out.println("The third");
}
//销毁方法,需要配置
public void destroyMethod(){
System.out.println("The fifth");
}
}
配置XML文件
通过Bean标签中的init-method属性与destroy-method属性设置初始化方法与销毁方法。
<bean id="beanTime" class="com.cjy.beanTime.Time" init-method="initMethod" destroy-method="destroyMethod">
<property name="time" value="15:02"> </property>
</bean>
验证输出结果
public void testBeanTime(){
ClassPathXmlApplicationContext context= new ClassPathXmlApplicationContext("beanTime.xml");
System.out.println("The four:获取对象");
Time time= context.getBean("beanTime", Time.class);
context.close();
}
生命周期中除了这基本的五步,还可以添加后置处理器,在初始化之前会对Bean进行处理,在初始化之后也会对Bean实例进行处理,使得生命周期变为七步。
创建后置处理器
public class MyBeanPost implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("After Postprocess");
return null;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("Before Postprocess");
return null;
}
}
在XML中配置后置处理器
在Bean的创建过程可以添加多个后置处理器,Bean创建过程中,同一个XML文件中配置的后置处理器都会运行。
<bean id="beanTime" class="com.cjy.beanTime.Time" init-method="initMethod" destroy-method="destroyMethod">
<property name="time" value="15:02"> </property>
</bean>
<bean id="post" class="com.cjy.beanTime.MyBeanPost"> </bean>
验证结果
public void testBeanTime(){
ClassPathXmlApplicationContext context= new ClassPathXmlApplicationContext("beanTime.xml");
System.out.println("The four:获取对象");
Time time= context.getBean("beanTime", Time.class);
context.close();
}
可以看到,多了两步。