1.Bean生命周期

(1)通过构造器创建bean实例(无参数构造)

(2)为bean的属性设置值和对其它bean引用(调用set方法)

(3)把bean实例传递bean前置处理器的方法 postProcessBeforeInitialization

(4)调用bean的初始化的方法(需要进行配置初始化的方法)

(5)把bean实例传递bean后置处理器的方法 postProcessAfterInitialization

(6)bean可以使用了(对象获取到了)

(7)当容器关闭时候,调用bean的销毁的方法(需要进行配置销毁的方法)

2.代码实现

(1)类

package com.leo.spring5.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class MyBeanPost implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("在初始化之前执行的方法");
return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
}

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("在初始化之后执行的方法");
return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
}
}
package com.leo.spring5.bean;

public class Life {

private String name;

// 无参数构造
public Life() {
System.out.println("第一步 执行无参数构造创建bean实例");
}

public void setName(String name) {
this.name = name;
System.out.println("第二步 调用set方法设置属性值");
}

// 创建执行的初始化的方法
public void initMethod() {
System.out.println("第三步 执行初始化的方法");
}
// 创建执行的小销毁的方法
public void destroyMethod() {
System.out.println("第五步 执行销毁的方法");
}
}

(2)配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
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-util.xsd">

<bean id="life" class="com.leo.spring5.bean.Life" init-method="initMethod" destroy-method="destroyMethod">
<property name="name" value="名称"></property>
</bean>
<!--配置后置处理器-->
<bean id="myBean" class="com.leo.spring5.bean.MyBeanPost"></bean>
</beans>

(3)测试文件

package com.leo.spring5.testdemo;

import com.leo.spring5.bean.Life;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestLife {
@Test
public void testLife() {
ApplicationContext context = new ClassPathXmlApplicationContext("bean-life.xml");
Life life = context.getBean("life", Life.class);
System.out.println("第四步 获取创建bean实例对象");
System.out.println(life);

// 手动让bean实例销毁
((ClassPathXmlApplicationContext) context).close();
}
}

3.执行结果

Spring5 Bean Bean生命周期 后置处理器_java