-
1.构造函数
-
2.set方法
-
3.后置处理器Before
-
4.初始化
-
5.后置处理器After
-
6.获取了bean对象
-
7.关闭
-
1.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<!--标签名శ:init method描述:设置bean属性后要调用的自定义初始化方法的名称。-->
<!--标签名称:destroy-method描述:在bean factory关闭时要调用的自定义销毁方法的名称。-->
<bean id="beanLifeCycle" class="test10month.test1012.BeanLifeCycle" init-method="initMethod"
destroy-method="destroy">
<property name="string" value="这是参数"/>
</bean>
<bean id="beanPostProcessorClass" class="test10month.test1012.BeanPostProcessorClass"/>
</beans>
2.类:
class BeanLifeCycle {
private String string;
public BeanLifeCycle() {
System.out.println("启动构造函数");
}
@Override
public String toString() {
return "BeanLifeCycle{" + "string='" + string + '\'' + '}';
}
public void setString(String string) {
this.string = string;
System.out.println("这是set方法");
}
public void initMethod() {
System.out.println("这是初始化");
}
public void destroy() {
System.out.println("这是关闭");
}
}
3.实现后置处理器的类
class BeanPostProcessorClass 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;
}
}
4.测试类
package test10month.test1012;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class BeanLifeCycleTest {
public static void main(String[] args) {
var context = new ClassPathXmlApplicationContext("test10month/test1012/BeanLifeCycleSpring.xml");
var beanLifeCycle = context.getBean("beanLifeCycle", BeanLifeCycle.class);
System.out.println("获取了bean对象");
System.out.println(beanLifeCycle);
context.close();
}
}