Spring中Bean的生命周期实例讲解
作者:程序小勇
这篇文章主要介绍了Spring中Bean的生命周期讲解,而Spring中的一个Bean从开始到结束经历很多过程,但总体可以分为六个阶段Bean定义、实例化、属性赋值、初始化、生存期、销毁,需要的朋友可以参考下
一、bean生命周期
其定义为:从对象的创建到销毁的过程。
而Spring中的一个Bean从开始到结束经历很多过程,但总体可以分为六个阶段Bean定义、实例化、属性赋值、初始化、生存期、销毁。
二、案例代码演示
1.首先我们来创建一个包,在包中创建一个Orders的对象,然后在对象中创建一个无参构造方法....
package Collectiona.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 bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("在初始化之后执行的方法。");
return bean;
}
}2.SpringBean生命周期中的增强接口PostProcessor;
postProcessBeforeInitialization方法执行前,会执行很多Aware类型的接口,这种类型接口作用是加载资源到Spring容器中。
我们在创建一个MyBeanPost的类来实现BeanPostProcessor接口。
package Collectiona.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 bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("在初始化之后执行的方法。");
return bean;
}
}3.在xml文件中配置相关信息。初始化方式,配置的init-method;最后容器销毁,配置的destroy-method.
<?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">
<bean id="orders" class="Collectiona.bean.Orders" init-method="initMethod" destroy-method="destroyMethod">
<property name="oname" value=""></property>
</bean>
<bean id="myBeanPost" class="Collectiona.bean.MyBeanPost">
</bean>
</beans>4.最后是进行测试输出:
package Collectiona.testSpring;
import Collectiona.bean.Orders;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class demo {
public static void main(String[] args) {
ClassPathXmlApplicationContext("classpath:Bean4.xml");
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:Bean4.xml");
Orders orders = context.getBean("orders",Orders.class);
System.out.println("第四步:获取bean的实例对象");
System.out.println(orders);
context.close();
}
}最终输出的结果是:

到此这篇关于Spring中Bean的生命周期实例讲解的文章就介绍到这了,更多相关Bean的生命周期内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
