百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

Spring Bean的生命周期(非常详细),看这个你就懂了

toyiye 2024-09-04 20:10 5 浏览 0 评论

Spring作为当前Java最流行、最强大的轻量级框架,受到了程序员的热烈欢迎。准确的了解Spring Bean的生命周期是非常必要的。我们通常使用ApplicationContext作为Spring容器。这里,我们讲的也是 ApplicationContext中Bean的生命周期。而实际上BeanFactory也是差不多的,只不过处理器需要手动注册。

转载请注明地址 http://www.cnblogs.com/zrtqsk/p/3735273.html,谢谢。

一、生命周期流程图:

Spring Bean的完整生命周期从创建Spring容器开始,直到最终Spring容器销毁Bean,这其中包含了一系列关键点。

若容器注册了以上各种接口,程序那么将会按照以上的流程进行。下面将仔细讲解各接口作用。

二、各种接口方法分类

Bean的完整生命周期经历了各种方法调用,这些方法可以划分为以下几类:

1、Bean自身的方法 : 这个包括了Bean本身调用的方法和通过配置文件中<bean>的init-method和destroy-method指定的方法

2、Bean级生命周期接口方法 : 这个包括了BeanNameAware、BeanFactoryAware、InitializingBean和DiposableBean这些接口的方法

3、容器级生命周期接口方法 : 这个包括了InstantiationAwareBeanPostProcessor 和 BeanPostProcessor 这两个接口实现,一般称它们的实现类为“后处理器”。

4、工厂后处理器接口方法 : 这个包括了AspectJWeavingEnabler, ConfigurationClassPostProcessor, CustomAutowireConfigurer等等非常有用的工厂后处理器 接口的方法。工厂后处理器也是容器级的。在应用上下文装配配置文件之后立即调用。

三、演示

我们用一个简单的Spring Bean来演示一下Spring Bean的生命周期。

1、首先是一个简单的Spring Bean,调用Bean自身的方法和Bean级生命周期接口方法,为了方便演示,它实现了BeanNameAware、BeanFactoryAware、InitializingBean和DiposableBean这4个接口,同时有2个方法,对应配置文件中<bean>的init-method和destroy-method。如下:

 package springBeanTest;
 
 import org.springframework.beans.BeansException;
 import org.springframework.beans.factory.BeanFactory;
 import org.springframework.beans.factory.BeanFactoryAware;
 import org.springframework.beans.factory.BeanNameAware;
 import org.springframework.beans.factory.DisposableBean;
 import org.springframework.beans.factory.InitializingBean;
 
 /**
 * @author qsk
 */
 public class Person implements BeanFactoryAware, BeanNameAware,
 InitializingBean, DisposableBean {
 
 private String name;
 private String address;
 private int phone;
 
 private BeanFactory beanFactory;
 private String beanName;
 
 public Person() {
 System.out.println("【构造器】调用Person的构造器实例化");
 }
 
 public String getName() {
 return name;
 }
 public void setName(String name) {
 System.out.println("【注入属性】注入属性name");
 this.name = name;
 }
 
 public String getAddress() {
 return address;
 }
 
 public void setAddress(String address) {
 System.out.println("【注入属性】注入属性address");
 this.address = address;
 }
 
 public int getPhone() {
 return phone;
 }
 
 public void setPhone(int phone) {
 System.out.println("【注入属性】注入属性phone");
 this.phone = phone;
 }
 
 @Override
 public String toString() {
 return "Person [address=" + address + ", name=" + name + ", phone="
 + phone + "]";
 }
 
 // 这是BeanFactoryAware接口方法
 @Override
 public void setBeanFactory(BeanFactory arg0) throws BeansException {
 System.out
 .println("【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()");
 this.beanFactory = arg0;
 }
 
 // 这是BeanNameAware接口方法
 @Override
 public void setBeanName(String arg0) {
 System.out.println("【BeanNameAware接口】调用BeanNameAware.setBeanName()");
 this.beanName = arg0;
 }
 
 // 这是InitializingBean接口方法
 @Override
 public void afterPropertiesSet() throws Exception {
 System.out
 .println("【InitializingBean接口】调用InitializingBean.afterPropertiesSet()");
 }
 // 这是DiposibleBean接口方法
 @Override
 public void destroy() throws Exception {
 System.out.println("【DiposibleBean接口】调用DiposibleBean.destory()");
 }
 
 // 通过<bean>的init-method属性指定的初始化方法
 public void myInit() {
 System.out.println("【init-method】调用<bean>的init-method属性指定的初始化方法");
 }
 
 // 通过<bean>的destroy-method属性指定的初始化方法
 public void myDestory() {
 System.out.println("【destroy-method】调用<bean>的destroy-method属性指定的初始化方法");
 }
 }

2、接下来是演示BeanPostProcessor接口的方法,如下:

 package springBeanTest;
 
 import org.springframework.beans.BeansException;
 import org.springframework.beans.factory.config.BeanPostProcessor;
 
 public class MyBeanPostProcessor implements BeanPostProcessor {
 public MyBeanPostProcessor() {
 super();
 System.out.println("这是BeanPostProcessor实现类构造器!!");
 // TODO Auto-generated constructor stub
 }
 
 @Override
 public Object postProcessAfterInitialization(Object arg0, String arg1)
 throws BeansException {
 System.out
 .println("BeanPostProcessor接口方法postProcessAfterInitialization对属性进行更改!");
 return arg0;
 }
 
 @Override
 public Object postProcessBeforeInitialization(Object arg0, String arg1)
 throws BeansException {
 System.out
 .println("BeanPostProcessor接口方法postProcessBeforeInitialization对属性进行更改!");
 return arg0;
 }
 }

如上,BeanPostProcessor接口包括2个方法postProcessAfterInitialization和postProcessBeforeInitialization,这两个方法的第一个参数都是要处理的Bean对象,第二个参数都是Bean的name。返回值也都是要处理的Bean对象。这里要注意。

3、InstantiationAwareBeanPostProcessor 接口本质是BeanPostProcessor的子接口,一般我们继承Spring为其提供的适配器类InstantiationAwareBeanPostProcessor Adapter来使用它,如下:

package springBeanTest;
import java.beans.PropertyDescriptor;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
public class MyInstantiationAwareBeanPostProcessor extends
 InstantiationAwareBeanPostProcessorAdapter {
 public MyInstantiationAwareBeanPostProcessor() {
 super();
 System.out
 .println("这是InstantiationAwareBeanPostProcessorAdapter实现类构造器!!");
 }
 // 接口方法、实例化Bean之前调用
 @Override
 public Object postProcessBeforeInstantiation(Class beanClass,
 String beanName) throws BeansException {
 System.out
 .println("InstantiationAwareBeanPostProcessor调用postProcessBeforeInstantiation方法");
 return null;
 }
 // 接口方法、实例化Bean之后调用
 @Override
 public Object postProcessAfterInitialization(Object bean, String beanName)
 throws BeansException {
 System.out
 .println("InstantiationAwareBeanPostProcessor调用postProcessAfterInitialization方法");
 return bean;
 }
 // 接口方法、设置某个属性时调用
 @Override
 public PropertyValues postProcessPropertyValues(PropertyValues pvs,
 PropertyDescriptor[] pds, Object bean, String beanName)
 throws BeansException {
 System.out
 .println("InstantiationAwareBeanPostProcessor调用postProcessPropertyValues方法");
 return pvs;
 }
}

这个有3个方法,其中第二个方法postProcessAfterInitialization就是重写了BeanPostProcessor的方法。第三个方法postProcessPropertyValues用来操作属性,返回值也应该是PropertyValues对象。

4、演示工厂后处理器接口方法,如下:

package springBeanTest;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
 public MyBeanFactoryPostProcessor() {
 super();
 System.out.println("这是BeanFactoryPostProcessor实现类构造器!!");
 }
 @Override
 public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0)
 throws BeansException {
 System.out
 .println("BeanFactoryPostProcessor调用postProcessBeanFactory方法");
 BeanDefinition bd = arg0.getBeanDefinition("person");
 bd.getPropertyValues().addPropertyValue("phone", "110");
 }
}

5、配置文件如下beans.xml,很简单,使用ApplicationContext,处理器不用手动注册:

<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="
 http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
 <bean id="beanPostProcessor" class="springBeanTest.MyBeanPostProcessor">
 </bean>
 <bean id="instantiationAwareBeanPostProcessor" class="springBeanTest.MyInstantiationAwareBeanPostProcessor">
 </bean>
 <bean id="beanFactoryPostProcessor" class="springBeanTest.MyBeanFactoryPostProcessor">
 </bean>
 
 <bean id="person" class="springBeanTest.Person" init-method="myInit"
 destroy-method="myDestory" scope="singleton" p:name="张三" p:address="广州"
 p:phone="15900000000" />
</beans>

6、下面测试一下:

package springBeanTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class BeanLifeCycle {
 public static void main(String[] args) {
 System.out.println("现在开始初始化容器");
 
 ApplicationContext factory = new ClassPathXmlApplicationContext("springBeanTest/beans.xml");
 System.out.println("容器初始化成功"); 
 //得到Preson,并使用
 Person person = factory.getBean("person",Person.class);
 System.out.println(person);
 
 System.out.println("现在开始关闭容器!");
 ((ClassPathXmlApplicationContext)factory).registerShutdownHook();
 }
}

关闭容器使用的是实际是AbstractApplicationContext的钩子方法。

我们来看一下结果:现在开始初始化容器

2014-5-18 15:46:20 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@19a0c7c: startup date [Sun May 18 15:46:20 CST 2014]; root of context hierarchy
2014-5-18 15:46:20 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [springBeanTest/beans.xml]
这是BeanFactoryPostProcessor实现类构造器!!
BeanFactoryPostProcessor调用postProcessBeanFactory方法
这是BeanPostProcessor实现类构造器!!
这是InstantiationAwareBeanPostProcessorAdapter实现类构造器!!
2014-5-18 15:46:20 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@9934d4: defining beans [beanPostProcessor,instantiationAwareBeanPostProcessor,beanFactoryPostProcessor,person]; root of factory hierarchy
InstantiationAwareBeanPostProcessor调用postProcessBeforeInstantiation方法
【构造器】调用Person的构造器实例化
InstantiationAwareBeanPostProcessor调用postProcessPropertyValues方法
【注入属性】注入属性address
【注入属性】注入属性name
【注入属性】注入属性phone
【BeanNameAware接口】调用BeanNameAware.setBeanName()
【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()
BeanPostProcessor接口方法postProcessBeforeInitialization对属性进行更改!
【InitializingBean接口】调用InitializingBean.afterPropertiesSet()
【init-method】调用<bean>的init-method属性指定的初始化方法
BeanPostProcessor接口方法postProcessAfterInitialization对属性进行更改!
InstantiationAwareBeanPostProcessor调用postProcessAfterInitialization方法
容器初始化成功
Person [address=广州, name=张三, phone=110]
现在开始关闭容器!
【DiposibleBean接口】调用DiposibleBean.destory()
【destroy-method】调用<bean>的destroy-method属性指定的初始化方法

本文到这里就结束了 下面我分享一些JAVA高级开发架构方面以及最新一线互联网大厂的面试题(如下图),免费分享给大家,希望能对各位有位帮助。

关注我的头条号 并在后台私信我:【java】即可(免费获取)

关注我的头条号 并在后台私信我:【java】即可(免费获取)

  • 关注、转发、评论后:私信小编发送“源码”(免费获取)(私信不要多字,不要少字,不要错字)

相关推荐

# Python 3 # Python 3字典Dictionary(1)

Python3字典字典是另一种可变容器模型,且可存储任意类型对象。字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中,格式如...

Python第八课:数据类型中的字典及其函数与方法

Python3字典字典是另一种可变容器模型,且可存储任意类型对象。字典的每个键值...

Python中字典详解(python 中字典)

字典是Python中使用键进行索引的重要数据结构。它们是无序的项序列(键值对),这意味着顺序不被保留。键是不可变的。与列表一样,字典的值可以保存异构数据,即整数、浮点、字符串、NaN、布尔值、列表、数...

Python3.9又更新了:dict内置新功能,正式版十月见面

机器之心报道参与:一鸣、JaminPython3.8的热乎劲还没过去,Python就又双叒叕要更新了。近日,3.9版本的第四个alpha版已经开源。从文档中,我们可以看到官方透露的对dic...

Python3 基本数据类型详解(python三种基本数据类型)

文章来源:加米谷大数据Python中的变量不需要声明。每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。在Python中,变量就是变量,它没有类型,我们所说的"类型"是变...

一文掌握Python的字典(python字典用法大全)

字典是Python中最强大、最灵活的内置数据结构之一。它们允许存储键值对,从而实现高效的数据检索、操作和组织。本文深入探讨了字典,涵盖了它们的创建、操作和高级用法,以帮助中级Python开发...

超级完整|Python字典详解(python字典的方法或操作)

一、字典概述01字典的格式Python字典是一种可变容器模型,且可存储任意类型对象,如字符串、数字、元组等其他容器模型。字典的每个键值key=>value对用冒号:分割,每个对之间用逗号,...

Python3.9版本新特性:字典合并操作的详细解读

处于测试阶段的Python3.9版本中有一个新特性:我们在使用Python字典时,将能够编写出更可读、更紧凑的代码啦!Python版本你现在使用哪种版本的Python?3.7分?3.5分?还是2.7...

python 自学,字典3(一些例子)(python字典有哪些基本操作)

例子11;如何批量复制字典里的内容2;如何批量修改字典的内容3;如何批量修改字典里某些指定的内容...

Python3.9中的字典合并和更新,几乎影响了所有Python程序员

全文共2837字,预计学习时长9分钟Python3.9正在积极开发,并计划于今年10月发布。2月26日,开发团队发布了alpha4版本。该版本引入了新的合并(|)和更新(|=)运算符,这个新特性几乎...

Python3大字典:《Python3自学速查手册.pdf》限时下载中

最近有人会想了,2022了,想学Python晚不晚,学习python有前途吗?IT行业行业薪资高,发展前景好,是很多求职群里严重的香饽饽,而要进入这个高薪行业,也不是那么轻而易举的,拿信工专业的大学生...

python学习——字典(python字典基本操作)

字典Python的字典数据类型是基于hash散列算法实现的,采用键值对(key:value)的形式,根据key的值计算value的地址,具有非常快的查取和插入速度。但它是无序的,包含的元素个数不限,值...

324页清华教授撰写【Python 3 菜鸟查询手册】火了,小白入门字典

如何入门学习python...

Python3.9中的字典合并和更新,了解一下

全文共2837字,预计学习时长9分钟Python3.9正在积极开发,并计划于今年10月发布。2月26日,开发团队发布了alpha4版本。该版本引入了新的合并(|)和更新(|=)运算符,这个新特性几乎...

python3基础之字典(python中字典的基本操作)

字典和列表一样,也是python内置的一种数据结构。字典的结构如下图:列表用中括号[]把元素包起来,而字典是用大括号{}把元素包起来,只不过字典的每一个元素都包含键和值两部分。键和值是一一对应的...

取消回复欢迎 发表评论:

请填写验证码