(九)Spring教程——ApplicationContext中Bean的生命周期

1.前言

        ApplicationContext中Bean的生命周期和BeanFactory中的生命周期类似,不同的是,如果Bean实现了org.springframework.context.ApplicationContextAware接口,则会增加一个调用该接口方法setApplicationContext()的步骤。

        此外,如果在配置文件中声明了工厂后处理器接口BeanFacotryPostProcessor的实现类,则应用上下文在装载配置文件后、初始化Bean实例之前将调用这些BeanFactoryPostProcessor对配置信息进行加工处理。Spring框架提供了多个工厂后处理器,如CustomEditorConfigurer、PopertyPlaceholderConfigurer等。如果在配置文件中定义了多个工厂后处理器,那么最好让它们实现org.springframework.core.Ordered接口,以便Spring以确定的顺序调用它们。工厂后处理器是容器级的,仅在应用上下文初始化时调用依次,其目的是完成一些配置文件的加工处理工作。

         ApplicationContext和BeanFactory另一个最大的不同之处在于:前者会利用Java反射机制自动识别出配置文件中定义的BeanPostProcessor、InstantiationAwareBeanPostProcessor和BeanFactoryPostProcessor,并自动将它们注册到应用上下文中;而后者需要在代码中通过手工调用addBeanPostProcessor()方法进行注册。这也是为什么在应用开发时普遍使用ApplicationContext而很少使用BeanFactory的原因之一。

       在ApplicationContext中,只需要在配置文件中通过<bean>定义工厂后处理器和Bean后处理器,它们就会按预期的方式运行。

2.创建Car类

        首先,我们对上一篇文章中的Car类稍微修改以下,修改后的代码如下:

package com.example.servlet001.bean;import org.springframework.beans.BeansException;import org.springframework.beans.factory.*;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;// 管理Bean生命周期的接口public class Car implements BeanFactoryAware, BeanNameAware, InitializingBean, DisposableBean, ApplicationContextAware {private  String brand;private String color;private int maxSpeed;private BeanFactory beanFactory;private String beanName;public Car(){System.out.println("调用Car()构造函数");}//InitializingBean接口方法@Overridepublic void afterPropertiesSet() throws Exception {System.out.println("调用InitializingBean.afterPropertiesSet()。");}//BeanNameAware接口方法@Overridepublic void setBeanName(String s) {System.out.println("调用BeanName.setBeanName().");this.beanName=s;}//BeanFactoryAware接口方法@Overridepublic void setBeanFactory(BeanFactory beanFactory) throws BeansException {System.out.println("调用BeanFactoryAware.setBeanFactory()");this.beanFactory=beanFactory;}//DisposableBean接口方法@Overridepublic void destroy() throws Exception {System.out.println("调用DisposableBean.destroy()。");}//通过<bean>的init-method属性指定的初始化方法public void myInit(){System.out.println("调用init-method所指定的myInit(),将maxSpeed设置为240。");this.maxSpeed=240;}//通过<bean>的destroy-method属性指定的销毁方法public void myDestroy(){System.out.println("调用destroy-method所指定的myDestroy()。");}public String getBrand(){return brand;}public void setBrand(String brand){System.out.println("调用setBrand()设置属性。");this.brand=brand;}public String getColor(){return color;}public void setColor(String color){this.color=color;}public int getMaxSpeed(){return maxSpeed;}public void setMaxSpeed(int maxSpeed){this.maxSpeed=maxSpeed;}public void introduce(){System.out.println("brand:"+brand+";color:"+color+";maxSpeed:"+maxSpeed);}@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {System.out.println("这是ApplicationContextAware的setApplicationContext()方法");}}

3.定义工厂后处理器

        定义一个工厂后处理器,MyBeanFactoryPostProcessor.java,该类的代码如下:

package com.example.servlet001;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 {//对car的brand属性配置信息进行“偷梁换柱”的加工操作@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory bf) throws BeansException {BeanDefinition bd=bf.getBeanDefinition("car1");bd.getPropertyValues().addPropertyValue("brand","奇瑞QQ");System.out.println("调用BeanFactoryPostProcessor.postProcessBeanFactory()");}}

        ApplicationContext在启动时,将首先为配置文件中的每个<bean>生成一个BeanDefinition对象,BeanDefinition是<bean>在Spring容器中的内部表示。当配置文件中所有的<bean>都被解析成BeanDefinition时,ApplicationContext将调用工厂后处理器的方法,因此,有机会通过程序的方式调整Bean的配置信息。在该后处理器中,将car1对应的BeanDefinition进行调整,将brand属性设置为“奇瑞QQ” 。

4.BeanPostProcessror实现类

        此外,还提供了一个BeanPostProcessror实现类,在该类中仅对car Bean进行处理,对配置文件所提供的属性设置值进行判断,并执行相应的“查漏补缺”操作,MyBeanPostProcessor.java的代码如下图所示:

package com.example.servlet001;import com.example.servlet001.bean.Car;import org.springframework.beans.BeansException;import org.springframework.beans.factory.config.BeanPostProcessor;public class MyBeanPostProcessor implements BeanPostProcessor {@Overridepublic Object postProcessBeforeInitialization(Object o, String s) throws BeansException {if(s.equals("car1")){Car car = (Car)o;if(car.getColor() == null){System.out.println("调用MyBeanPostProcessor.postProcessBeforeInitialization(),color为空,设置为默认黑色。");car.setColor("黑色");}}return o;}@Overridepublic Object postProcessAfterInitialization(Object o, String s) throws BeansException {if(s.equals("car1")){Car car = (Car)o;if(car.getMaxSpeed() >= 200){System.out.println("调用MyBeanPostProcessor.postProcessAfterInitialization(),将maxSpeed调整为200。");car.setMaxSpeed(200);}}return o;}}

5.容器级后处理器

      MyInstantiationAwareBeanPostProcessor.java代码如下

package com.example.servlet001;import org.springframework.beans.BeansException;import org.springframework.beans.PropertyValues;import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;import java.beans.PropertyDescriptor;public class MyInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter {@Overridepublic Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {if("car1".equals(beanName)){System.out.println("MyInstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation");}return null;}@Overridepublic boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {if("car1".equals(beanName)){System.out.println("InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation");}return true;}@Overridepublic PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {if("car1".equals(beanName)){System.out.println("InstantiationAwareBeanPostProcessor.postProcessPropertyValues");}return pvs;}}

6.配置文件

修改resource文件夹下的test.xml配置文件,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"xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"><!--这个brand属性的值将会被工厂处理器更改掉--><bean id="car1" name="car1" class="com.example.servlet001.bean.Car"init-method="myInit"destroy-method="myDestroy"p:brand="红旗"p:maxSpeed="200"/><!--容器级声明周期处理--><bean id="myInstantiationAwareBeanPostProcessor" class="com.example.servlet001.MyInstantiationAwareBeanPostProcessor"></bean><!--注册Bean后处理器--><bean id="myBeanPostProcessor"class="com.example.servlet001.MyBeanPostProcessor"></bean><!--工厂后处理器--><bean id="myBeanFactoryPostProcessor"class="com.example.servlet001.MyBeanFactoryPostProcessor"></bean></beans>

7.结果验证

        创建一个Demo1.java类来测试该配置的运行效果,Demo1.java代码如下图所示:

package com.example.servlet001;import com.example.servlet001.bean.Car;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Demo1 {public static void main(String[] args) {ApplicationContext ac = new ClassPathXmlApplicationContext("test.xml");Car car=(Car)ac.getBean("car1");car.introduce();}}

点击运行后的结果如图所示

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/22513.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

NeMo训练llama2_7b(不用NeMo-Framework-Launcher)

TOC 本文介绍了NeMo如何训练llama2_7b模型 1.参考链接 支持的模型列表功能特性LLAMA2端到端流程(基于NeMo-Framework-Launcher) 2.创建容器 docker run --gpus all --shm-size32g -ti -e NVIDIA_VISIBLE_DEVICESall \--privileged --nethost -v $PWD:/home \-w /home --na…

香橙派 Orange AIpro 测评记录视频硬件解码

香橙派 Orange AIpro 测评记录视频硬件解码 香橙派官网&#xff1a;http://www.orangepi.cn/ 收到了一块Orange Pi AIpro开发板&#xff0c;记录一下我的测评~测评简介如下&#xff1a;1.连接网络2.安装流媒体进行硬件解码测试3.安装IO测试 简介 Orange Pi AI Pro 是香橙派联合…

0基础学习区块链技术——链之间数据同步样例

我们可以在https://blockchaindemo.io/体验这个过程。 创建区块 默认第一个链叫Satoshi(中本聪)。链上第一个区块叫“创世区块”——Genesis Block。后面我们会看到创建的第二条链第一个区块也是如此。 新增链 新创建的链叫Debby。默认上面有一个创世区块。 然后我们让这…

Android自定义View - LayoutParams

这一期我们来讲一讲LayoutParams这个玩意儿。Android入门的第一行代码就牵扯到这个东西&#xff0c;然而&#xff0c;你真的理解够了吗&#xff1f; 第一层理解 <RelativeLayout xmlns:android"http://schemas.android.com/apk/res/android"xmlns:app"http…

C# 中文字符串转GBK字节的示例

一、编写思路 在 C# 中&#xff0c;将中文字符串转换为 GBK 编码的字节数组需要使用 Encoding 类。然而&#xff0c;Encoding 类虽然默认并不直接支持 GBK 编码&#xff0c;但是可以通过以下方式来实现这一转换&#xff1a; 1.使用系统已安装的编码提供者&#xff08;如果系统…

数据库查询字段在哪个数据表中

问题的提出 当DBA运维多个数据库以及多个数据表的时候&#xff0c;联合查询是必不可少的。则数据表的字段名称是需要知道在哪些数据表中存在的。故如下指令&#xff0c;可能会帮助到你&#xff1a; 问题的处理 查找sysinfo这个字段名称都存在哪个数据库中的哪个数据表 SELEC…

大模型日报2024-06-04

大模型日报 2024-06-04 大模型资讯 1-bit LLMs或能解决AI的能耗问题 摘要: 大型语言模型&#xff08;如ChatGPT&#xff09;的性能不断提升&#xff0c;但其规模也在扩大。1-bit LLMs有望在保持高性能的同时&#xff0c;大幅降低能耗&#xff0c;解决AI系统的能源需求问题。 Hu…

Ubuntu系统设置Redis与MySQL登录密码

Ubuntu系统设置Redis与MySQL登录密码 在Ubuntu 20.04系统中配置Redis和MySQL的密码&#xff0c;您需要分别对两个服务进行配置。以下是详细步骤&#xff1a; 配置Redis密码 打开Redis配置文件: Redis的配置文件通常位于/etc/redis/redis.conf。 sudo nano /etc/redis/redis.c…

从实战案例来学习结构化提示词(一)

大家好,我是木易,一个持续关注AI领域的互联网技术产品经理,国内Top2本科,美国Top10 CS研究生,MBA。我坚信AI是普通人变强的“外挂”,所以创建了“AI信息Gap”这个公众号,专注于分享AI全维度知识,包括但不限于AI科普,AI工具测评,AI效率提升,AI行业洞察。关注我,AI之…

C# 获取windows的上传下载速度

直接利用CZGL.SystemInfo代码 UnitType.cs /// <summary> /// 单位 /// </summary> public enum UnitType : int {/// <summary>/// Byte/// </summary>/// B 0,/// <summary>/// KB/// </summary>KB,/// <summary>/// MB/// </…

Python语法详解module1(变量、数据类型)

目录 一、变量1. 变量的概念2. 创建变量3. 变量的修改4. 变量的命名 二、数据类型1. Python中的数据类型2. 整型&#xff08;int&#xff09;3. 浮点型&#xff08;float&#xff09;4. 布尔型&#xff08;bool&#xff09;5. 字符串&#xff08;str&#xff09;6.复数&#xf…

MySQL中所有常见知识点汇总

存储引擎 这一张是关于整个存储引擎的汇总知识了。 MySQL体系结构 这里是MySQL的体系结构图&#xff1a; 一般将MySQL分为server层和存储引擎两个部分。 其实MySQL体系结构主要分为下面这几个部分&#xff1a; 连接器&#xff1a;负责跟客户端建立连 接、获取权限、维持和管理…

JavaScript第九讲BOM编程的练习题

前言 上一节有BOM的讲解&#xff0c;有需要的码客们可以去看一下 以下是一个结合了上述BOM&#xff08;Browser Object Model&#xff09;相关内容的练习题及其源代码示例&#xff1a; 练习题&#xff1a; 编写一个JavaScript脚本&#xff0c;该脚本应该执行以下操作&#…

1141. 查询近30天活跃用户数

1141. 查询近30天活跃用户数 题目链接&#xff1a;1141. 查询近30天活跃用户数 代码如下&#xff1a; # Write your MySQL query statement below select activity_date as day,count(distinct user_id) as active_users from Activity where activity_date between 2019-06-…

[数据集][图像分类]蘑菇分类数据集14689张50类别

数据集类型&#xff1a;图像分类用&#xff0c;不可用于目标检测无标注文件 数据集格式&#xff1a;仅仅包含jpg图片&#xff0c;每个类别文件夹下面存放着对应图片 图片数量(jpg文件个数)&#xff1a;14689 分类类别数&#xff1a;50 类别名称:[“agaricus_augustus”,“agari…

流程引擎,灵活设计业务流程的编辑器设计

流程引擎&#xff0c;灵活设计业务流程的编辑器设计

PySpark特征工程(I)--数据预处理

有这么一句话在业界广泛流传&#xff1a;数据和特征决定了机器学习的上限&#xff0c;而模型和算法只是逼近这个上限而已。由此可见&#xff0c;特征工程在机器学习中占有相当重要的地位。在实际应用当中&#xff0c;可以说特征工程是机器学习成功的关键。 特征工程是数据分析…

若依项目部署(Linux2.0)

解压jdk tar -zxvf jdk-8u151-linux-x64.tar.gz 配置Java环境变量&#xff1a; vim /etc/profile 设置环境变量生效&#xff1a; source /etc/profile 查看一下jdk版本&#xff1a; java -version 解压tomcat tar -zxvf apache-tomcat-8.5.20.tar.gz 防火墙设置&#xff1a; …

一款WPF的小巧MVVM框架——stylet框架初体验

今天偶然知道有一款叫做stylet的MVVM框架&#xff0c;挺小巧的&#xff0c;特别是它的命令触发方式&#xff0c;简单粗暴&#xff0c;让人感觉很神器。所以接下来我要做一个简单的demo&#xff0c;顺便来分享给大家。 本地创建一个WPF项目&#xff0c;此处我使用.NET 8来创建。…

前端 JS 经典:阿里云文件上传思路

前言&#xff1a;功能点概括&#xff1a;1、多选文件 2、选择文件夹 3、拖拽 4、选择后形成一个列表&#xff0c;列表里有一些信息 5、有进度条 6、控制并发数 7、可取消 8、展示统计信息 1. 交互实现 交互的目标是要拿到 file 对象。只要拿到 file 对象&#xff0c;就能通过…