spring01-spring容器启动过程分析

news2024/9/20 8:08:21

【README】

本文总结自《spring揭秘》,作者王福强,非常棒的一本书,墙裂推荐;

spring容器根据配置元素组装可用系统分2个阶段,包括spring容器启动, springbean实例化阶段; 本文详细分析spring容器启动阶段;


【1】Spring容器根据配置元素组装可用系统的过程

Spring容器根据配置元素组装可用系统的过程,有2个阶段:

  • spring容器启动;
  • springbean实例化;
    在这里插入图片描述

容器启动阶段: 加载配置元数据(xml文件),然后使用工具类如 BeanDefinitionReader对加载的配置元数据进行解析,并将结果编组为 BeanDefinition ,注册到相应的 BeanDefinitionRegistry,这样容器启动工作就完成了;

Bean实例化阶段: 容器会首先检查所请求的对象之前是否已经初始化,若没有,则根据注册的BeanDefinition实例化bean,并为其注入依赖。 如果该对象实现了某些回调接口,也会根据回调接口的要求来装配它; 当该对象被装配完成后 ,容器会立即将其返回给请求方使用;


【2】BeanFactoryPostProcessor-Bean工厂后置处理器

BeanFactoryPostProcessor: Spring提供了叫做 BeanFactoryPostProcessor 容器扩展机制; 该机制允许我们在容器启动阶段完成后新增逻辑;

常用BeanFactoryPostProcessor:

  1. PropertySourcePlaceHolderConfigurer:属性占位符配置器, 如jdbc连接串属性通过properties文件的属性值 替换 占位符;
  2. PropertyOverrideConfigurer : 属性覆盖替换配置器;如修改属性值;
  3. CustomEditorConfigurer:自定义编辑器配置器,用于不同数据格式间的转换;

【补充】

(1)上述2个BeanFactoryPostProcessor 都是通过修改BeanDefinition 来对属性进行替换或修改的;

(2) CustomerEditorConfigurer:没有修改BeanDefinition,而是把后期要用到的信息注册到容器;

【2.1】属性占位符配置器使用场景代码

PropertySourcesPlaceholderConfigurer-属性占位符配置器使用场景:初始化数据库连接池属性, 并利用 PropertyOverrideConfigurer 重写属性值;

【PropertySourcesPlaceholderConfigurerMain】入口

public class PropertySourcesPlaceholderConfigurerMain {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans0404.xml");
        BasicDataSource dataSource = context.getBean("dataSource", BasicDataSource.class);
        System.out.println(dataSource.getUrl());
        System.out.println(dataSource.getUserName());
        System.out.println(dataSource.getDriverClassName());
    }
}

【beans0404.xml】

<!-- 为 PropertySourcesPlaceholderConfigurer 这个BeanFactoryPostProcessor 配置属性文件地址 -->
    <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
        <property name="locations">
            <value>jdbc.properties</value>
        </property>
    </bean>

    <!-- 为 PropertyOverrideConfigurer 这个BeanFactoryPostProcessor 配置重写属性文件的地址 -->
    <bean class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">
        <property name="locations" value="ds-pool-override.properties" />
    </bean>

    <!-- 数据源bean,其中属性值通过变量指定,变量通过 BeanFactoryPostProcessor 设置值-->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
        <property name="url">
            <value>${jdbc.url}</value>
        </property>
        <property name="driverClassName">
            <value>${jdbc.driverClassName}</value>
        </property>
        <property name="username">
            <value>${jdbc.username}</value>
        </property>
        <property name="password">
            <value>${jdbc.password}</value>
        </property>
    </bean>

【jdbc.properties】

jdbc.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.username=root
jdbc.password=root


【ds-pool-override.properties】重写属性值的属性文件

dataSource.username=rootOverride

【打印日志】

jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai
rootOverride
com.mysql.cj.jdbc.Driver

【2.2】CustomerEditorConfigurer-自定义编辑器配置器

应用场景: xml配置的bean信息都是字符串,但最终都要要转换为bean对象的,从字符串类型到对象类型的转换,就是由CustomerEditorConfigurer(EditorConfigurer)来完成的;

  • 只要为每种对象类型提供一个 PropertyEditor,就可以做类型转换

Spring 提供的PropertyEditor列表

  • (1) StringArrayPropertyEditor:把符合csv格式的字符串转换为String[] 数组的形式;类似的还有 ByteArrayPropertyEditor, CharArrayPropertyEditor;
  • (2) ClassEditor: 根据class名称转为 Class对象;
  • (3) FileEditor: file类型的PropertyEditor;类似的还有InputStreamEditor, URLEditor;
  • (4) LocaleEditor: 本地化转换;
  • (5) PatternEditor: 正则表达式转换

自定义属性编辑器PropertyEditor: 继承自 PropertyEditorSupport ; PropertyEditorSupport 实现了 PropertyEditor 接口; PropertyEditor 接口定义如下:

public interface PropertyEditor {

    void setValue(Object value);

    Object getValue();

    boolean isPaintable();
    
    void paintValue(java.awt.Graphics gfx, java.awt.Rectangle box);

    String getJavaInitializationString();

    String getAsText();
   
    void setAsText(String text) throws java.lang.IllegalArgumentException;
    
    String[] getTags();
    
    java.awt.Component getCustomEditor();

    boolean supportsCustomEditor();

    void addPropertyChangeListener(PropertyChangeListener listener);

    void removePropertyChangeListener(PropertyChangeListener listener);
}

【2.3】自定义编属性编辑器案例代码

自定义日期i字符串转日期类型的编辑器;

【CustomPropertyEditorMain】入口

public class CustomPropertyEditorMain {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans0404.xml");
        System.out.println(context.getBean("customDateDto", CustomDateDto.class));
    }
}

【beans0404.xml】

<!-- 自定义属性编辑器  -->
<bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    <property name="propertyEditorRegistrars">
        <list>
            <ref bean="customDatePropertEditroResigtrar" />
        </list>
    </property>
</bean>
<bean id="customDatePropertEditroResigtrar" class="com.tom.springnote.chapter04.t0404.CustomDatePropertEditroResigtrar">
    <property name="customDatePropertyEditor">
        <ref bean="customDatePropertyEditor"/>
    </property>
</bean>
<bean id="customDatePropertyEditor" class="com.tom.springnote.chapter04.t0404.CustomDatePropertyEditor">
    <property name="datePattern" value="yyyy-MM-dd" />
</bean>
<bean id="customDateDto" class="com.tom.springnote.chapter04.t0404.CustomDateDto">
    <property name="date" value="2024-08-04" />
</bean>

在这里插入图片描述

【CustomDatePropertEditroResigtrar】自定义日期属性编辑器注册器

public class CustomDatePropertEditroResigtrar implements PropertyEditorRegistrar {
    private PropertyEditor customDatePropertyEditor;
    @Override
    public void registerCustomEditors(PropertyEditorRegistry registry) {
        registry.registerCustomEditor(Date.class, getCustomDatePropertyEditor());
    }

    public PropertyEditor getCustomDatePropertyEditor() {
        return customDatePropertyEditor;
    }

    public void setCustomDatePropertyEditor(PropertyEditor customDatePropertyEditor) {
        this.customDatePropertyEditor = customDatePropertyEditor;
    }
}

【CustomDatePropertyEditor】自定义日期属性编辑器

public class CustomDatePropertyEditor extends PropertyEditorSupport {
    private String datePattern;

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        try {
            setValue(new SimpleDateFormat(getDatePattern()).parse(text));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    public String getDatePattern() {
        return datePattern;
    }

    public void setDatePattern(String datePattern) {
        this.datePattern = datePattern;
    }
}

【CustomDateDto】自定义dto (带date类型属性)

public class CustomDateDto {
    private Date date;

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    @Override
    public String toString() {
        return "CustomDateDto{" +
                "date=" + date +
                '}';
    }
}

【打印日志】 (把字符串2024-08-04转换为 date类型属性)

CustomDateDto{date=Sun Aug 04 00:00:00 CST 2024}

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

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

相关文章

Java项目通过IDEA远程debug调试

前言 在我们真实项目开发过程中&#xff0c;又是经常会发现一种问题&#xff0c;就是我们在开发环境功能是正常的&#xff0c;在测试环境可能也不太容易发现问题。 结果到了生产环境&#xff0c;由于数据量大&#xff0c;且数据类型变多后&#xff0c;就产生了一些比较难复现…

创客匠人对话(下):普通人做心理学IP为何如此成功?

老蒋创客圈第63期对话标杆直播连麦&#xff0c;我们邀请到【惢众身心成长家园平台】王辉老师。在上篇文章中&#xff0c;我们着重分享了王辉老师如何通过原有客源造流量&#xff0c;引爆大事件发售的核心秘籍。 本篇文章我们将继续分享对话精彩内容&#xff0c;深度剖析王辉老…

python两大编程思想,类和对象,实例变量类变量,静态方法与实例方法和类方法,给对象动态绑定属性和函数

1.两大编程思想 面向对象&#xff08;python和java&#xff09;和面向过程&#xff08;c语言&#xff09;编程思想的区别 2.类和对象 1.类是抽出对象中的相似属性和行为得到的类别 python中一切皆对象 对于字符串&#xff0c;整数等等都是类型class 可以自定义class&#x…

海康相机二次开发学习笔记2-方案的相关操作

方案和流程是VisionMaster(简称VM)的主要概念,一个方案可以包含多个流程,一个流程可以由多个模块通过连线建立逻辑关系. 方案的相关操作 1. 界面设计 界面分为三个部分:流程显示区,方案操作区,消息显示区.添加GroupBox,文本框,文本,和一些按钮. 2. 流程显示区 为了将方案加…

基于Spring Boot的可盈保险合同管理系统的设计与实现

TOC springboot146基于Spring Boot的可盈保险合同管理系统的设计与实现 绪论** 1.1 研究背景 当前社会各行业领域竞争压力非常大&#xff0c;随着当前时代的信息化&#xff0c;科学化发展&#xff0c;让社会各行业领域都争相使用新的信息技术&#xff0c;对行业内的各种相关…

论文复现_从 CONAN 中收集 TPL 数据集

1. 概述 CONAN&#xff1a;Conan是一个用于C项目的开源包管理工具。 它的主要目标是简化C项目的依赖关系管理过程&#xff0c;使开发人员能够更轻松地集成、构建和分享C库。 其中有一些比较独特的功能&#xff0c;例如&#xff1a;版本管理、第三方库管理等。 TPL 数据集&…

2.1 MySQL概述

欢迎来到我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;欢迎订阅相关专栏&#xff1a; 工&#x1f497;重&#x1f497;hao&#x1f497;&#xff1a;野老杂谈 ⭐️ 全网最全IT互联网公司面试宝典&#xff1a;收集整理全网各大IT互联网公司技术、项目、HR面试真题.…

多媒体技术及应用课程思政网站

摘 要 在Internet高速发展的今天&#xff0c;我们生活的各个领域都涉及到计算机的应用&#xff0c;其中包括多媒体技术及应用课程思政网站的网络应用&#xff0c;在外国多媒体技术及应用课程思政已经是很普遍的方式&#xff0c;不过国内的多媒体技术及应用课程思政可能还处于起…

【MIT-BEVFusion代码解读】第二篇:LiDAR的encoder部分

文章目录 1. Voxelization2. backbone2.1 稀疏卷积介绍2.2 SparseEncoder&#xff08;1&#xff09;输入输出及参数说明&#xff08;2&#xff09;流程 BEVFusion相关的其它文章链接&#xff1a; 【论文阅读】ICRA 2023|BEVFusion&#xff1a;Multi-Task Multi-Sensor Fusion w…

VPN远程同时连接:IPsec站点到站点方式及L2TPoverIPsecVPN方式

一、实验目的及拓扑 实验目的&#xff1a;企业总部与分支通过IPsecVPN建立点对点连接&#xff0c;移动端通过L2TP方式与企业总部连接 二、基本配置 1、如图所示配置接口地址 2、总部接口区域配置 [FW1]dis zone local priority is 100 interface of the zone is (0): # …

【数值计算方法】常微分方程初值问题的数值解法

常微分方程初边值问题数值解 第九章 1. 引言 微分方程 :含有未知函数及其导数或微分的等式; 除了少数特殊类型的微分方程能用解析方法求得精确解外 , 多数情况找不到解的解析表达式 本章研究两类常微分问题&#xff1a; 一阶常微分方程的初值问题 ; 两阶常微分方程边值问题 一…

C#小结:如何在VS2022中使用菜单栏中的Git管理代码

目录 第一部分&#xff1a;基础操作 第一步&#xff0c;登录官网&#xff0c;设置好邮箱&#xff0c;然后右上角新建仓库 第二步&#xff0c;提交代码到远程仓库中 第三步&#xff0c;查看和比对自己修改的内容 第四步&#xff0c;查看该项目所有提交历史记录 第五步&…

LAMM: Label Alignment for Multi-Modal Prompt Learning

系列论文研读目录 文章目录 系列论文研读目录文章题目含义AbstractIntroductionRelated WorkVision Language ModelsPrompt Learning MethodologyPreliminaries of CLIPLabel AlignmentHierarchical Loss 分层损失Parameter Space 参数空间Feature Space 特征空间Logits Space …

CSP-CCF 202009-1 检测点查询

一、问题描述 二、解答 提醒&#xff1a;本题不宜开方&#xff0c;距离间的比较用平方来比较更好 思路&#xff1a;使用三次for循环&#xff0c;逐一找到最小、第二小、第三小 注&#xff1a;这里用到了limits.h头文件&#xff0c;里面包含了int的最大值INT_MAX #include&l…

搭建企业博客:塑造品牌可信度与优化SEO的利器

引言 在数字化时代&#xff0c;信息的传播速度超乎想象&#xff0c;企业如何在这个信息爆炸的环境中脱颖而出&#xff0c;成为连接消费者、塑造品牌形象的关键。企业博客&#xff0c;作为一种低成本、高效率的营销与沟通工具&#xff0c;正逐渐成为企业策略中不可或缺的一环。…

阅读台灯什么品牌好?不良商家最常用的四大阅读台灯套路,需警惕

阅读台灯什么品牌好&#xff1f;市场上的护眼台灯种类繁多&#xff0c;众多选择中不乏以低价吸引消费者的产品&#xff0c;这也导致了部分家长对于护眼台灯的价值产生了质疑&#xff0c;认为它们不过是不必要的开销。确实&#xff0c;一些低质的护眼灯不仅使用了劣质材料&#…

利用minikube部署k8s集群并部署lnmp服务

部署minikube 参考官网进行安装部署 利用minikube部署k8s集群 1. 部署k8s集群 minikube start k8s集群部署lnmp 1. 将如下内容存储为lnmp.yaml文件 --- apiVersion: v1 kind: Namespace metadata: name: lnmp --- apiVersion: v1 kind: PersistentVolumeClaim metadata: na…

请注意,这是第一届程序化售卖广告的奥运会

作者&#xff1a;刀客doc 巴黎奥运会收官了。很多人在谈郑钦文的商业价值、哪个品牌押中了奥运冠军时&#xff0c;却忽略了一个新闻&#xff1a; 这是第一届程序化售卖广告的奥运会&#xff1a;NBC环球通过旗下的流媒体平台 Peacock&#xff0c;以程序化方式销售巴黎奥运会期…

基于java的私人牙科诊所管理系统

文章目录 项目介绍主要功能截图:部分代码展示设计总结项目获取方式🍅 作者主页:超级无敌暴龙战士塔塔开 🍅 简介:Java领域优质创作者🏆、 简历模板、学习资料、面试题库【关注我,都给你】 🍅文末获取源码联系🍅 项目介绍 基于java的私人牙科诊所管理系统,java项…

文心一言 VS 讯飞星火 VS chatgpt (325)-- 算法导论22.5 1题

一、如果在图G中加入一条新的边&#xff0c;G中的强连通分量的数量会发生怎样的变化&#xff1f;如果要写代码&#xff0c;请用go语言。 文心一言&#xff1a; 在图G中加入一条新的边&#xff0c;其对强连通分量&#xff08;Strongly Connected Components, SCCs&#xff09;…