spring之ApplicationContext

news2024/9/23 11:19:13

spring之ApplicationContext

  • ApplicationContext
    • ApplicationContext源码
    • ApplicationContext继承接口分析
    • ApplicationContext两个比较重要的实现类
      • AnnotationConfigApplicationContext
      • ClassPathXmlApplicationContext
    • 国际化---MessageSource
    • 资源加载---ResourceLoader
    • 获取运行时环境---Environment
    • 事件发布---ApplicationEventPublisher

ApplicationContext

ApplicationContext是个接口,实际上也是一个BeanFactory,不过比BeanFactory更加强大。

ApplicationContext源码

public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,
		MessageSource, ApplicationEventPublisher, ResourcePatternResolver {

	/**
	 * Return the unique id of this application context.
	 * @return the unique id of the context, or {@code null} if none
	 */
	@Nullable
	String getId();

	/**
	 * Return a name for the deployed application that this context belongs to.
	 * @return a name for the deployed application, or the empty String by default
	 */
	String getApplicationName();

	/**
	 * Return a friendly name for this context.
	 * @return a display name for this context (never {@code null})
	 */
	String getDisplayName();

	/**
	 * Return the timestamp when this context was first loaded.
	 * @return the timestamp (ms) when this context was first loaded
	 */
	long getStartupDate();

	/**
	 * Return the parent context, or {@code null} if there is no parent
	 * and this is the root of the context hierarchy.
	 * @return the parent context, or {@code null} if there is no parent
	 */
	@Nullable
	ApplicationContext getParent();

	/**
	 * Expose AutowireCapableBeanFactory functionality for this context.
	 * <p>This is not typically used by application code, except for the purpose of
	 * initializing bean instances that live outside of the application context,
	 * applying the Spring bean lifecycle (fully or partly) to them.
	 * <p>Alternatively, the internal BeanFactory exposed by the
	 * {@link ConfigurableApplicationContext} interface offers access to the
	 * {@link AutowireCapableBeanFactory} interface too. The present method mainly
	 * serves as a convenient, specific facility on the ApplicationContext interface.
	 * <p><b>NOTE: As of 4.2, this method will consistently throw IllegalStateException
	 * after the application context has been closed.</b> In current Spring Framework
	 * versions, only refreshable application contexts behave that way; as of 4.2,
	 * all application context implementations will be required to comply.
	 * @return the AutowireCapableBeanFactory for this context
	 * @throws IllegalStateException if the context does not support the
	 * {@link AutowireCapableBeanFactory} interface, or does not hold an
	 * autowire-capable bean factory yet (e.g. if {@code refresh()} has
	 * never been called), or if the context has been closed already
	 * @see ConfigurableApplicationContext#refresh()
	 * @see ConfigurableApplicationContext#getBeanFactory()
	 */
	AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException;

}

ApplicationContext继承接口分析

  1. HierarchicalBeanFactory:拥有获取父BeanFactory的功能

  2. ListableBeanFactory:拥有获取beanNames的功能

  3. ResourcePatternResolver:资源加载器,可以一次性获取多个资源(文件资源等等)

  4. EnvironmentCapable:可以获取运行时环境(没有设置运行时环境功能)

  5. ApplicationEventPublisher:拥有广播事件的功能(没有添加事件监听器的功能)

  6. MessageSource:拥有国际化功能

ApplicationContext两个比较重要的实现类

AnnotationConfigApplicationContext

类继承实现结构:
AnnotationConfigApplicationContext类继承实现结构

类图说明:

  1. ConfigurableApplicationContext:继承了ApplicationContext接口,增加了,添加事件监听器、添加BeanFactoryPostProcessor、设置Environment,获取ConfigurableListableBeanFactory等功能

  2. AbstractApplicationContext:实现了ConfigurableApplicationContext接口

  3. GenericApplicationContext:继承了AbstractApplicationContext,实现了BeanDefinitionRegistry接口,拥有了所有ApplicationContext的功能,并且可以注册BeanDefinition,注意这个类中有一个属性(DefaultListableBeanFactory beanFactory)

  4. AnnotationConfigRegistry:可以单独注册某个为类为BeanDefinition(可以处理该类上的**@Configuration注解**,已经可以处理**@Bean注解**),同时可以扫描

  5. AnnotationConfigApplicationContext:继承了GenericApplicationContext,实现了AnnotationConfigRegistry接口,拥有了以上所有的功能

ClassPathXmlApplicationContext

类继承实现结构:
ClassPathXmlApplicationContext类继承实现结构
它也是继承了AbstractApplicationContext,但是相对于AnnotationConfigApplicationContext而言,功能没有AnnotationConfigApplicationContext强大,比如不能注册BeanDefinition

国际化—MessageSource

messages.properties:

test=你好
demo=测试指定字符串{0}

messages_en.properties:

test=hello
demo=test str{0}

AppConfig:

    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("messages");
        return messageSource;
    }

Main:

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        //context.refresh();
        System.out.println(context.getMessage("test", null, Locale.getDefault()));
        System.out.println(context.getMessage("test", null, Locale.CHINA));
        System.out.println(context.getMessage("test", null, Locale.US));

        System.out.println(context.getMessage("demo", new String[]{"1"}, Locale.getDefault()));
        System.out.println(context.getMessage("demo", new String[]{"1"}, Locale.US));

    }

资源加载—ResourceLoader

    public static void main(String[] args) throws IOException {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

        Resource resource = context.getResource("file://D:\\javaProject\\tuling-code\\spring\\src\\main\\java\\top\\mingempty\\spring\\config\\AppConfig.java");

        System.out.println(resource.getFilename());
        System.out.println(resource.contentLength());


        Resource resource1 = context.getResource("https://www.baidu.com");
        System.out.println(resource1.contentLength());
        System.out.println(resource1.getURL());

        Resource resource2 = context.getResource("classpath:spring.xml");
        System.out.println(resource2.contentLength());
        System.out.println(resource2.getURL());


        //获取多个
        Resource[] resources = context.getResources("classpath:top/mingempty/spring/*");
        for (Resource resource3 : resources) {
            System.out.println(resource3.contentLength());
            System.out.println(resource3.getFilename());
        }
    }

获取运行时环境—Environment

AppConfig :

@PropertySource("classpath:spring.properties")
public class AppConfig {

}

spring.properties:

environment=Environment
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

        // 操作系统层面的环境变量
        Map<String, Object> systemEnvironment = context.getEnvironment().getSystemEnvironment();
        System.out.println(systemEnvironment);

        System.out.println("=======");


        // java运行层面,通过-D指定的
        Map<String, Object> systemProperties = context.getEnvironment().getSystemProperties();
        System.out.println(systemProperties);

        System.out.println("=======");

        // 前面两者之和
        MutablePropertySources propertySources = context.getEnvironment().getPropertySources();
        System.out.println(propertySources);

        System.out.println("=======");

        // 系统中存在的环境变量
        System.out.println(context.getEnvironment().getProperty("MVN_HOME"));

        System.out.println(context.getEnvironment().getProperty("sun.jnu.encoding"));

        // 获取一个不存在的
        System.out.println(context.getEnvironment().getProperty("NULL"));

        // 获取配置文件内的
        // @PropertySource("classpath:spring.properties")
        System.out.println(context.getEnvironment().getProperty("environment"));
        
    }

事件发布—ApplicationEventPublisher

AppConfig:注册一个监听事件

public class AppConfig {
    @Bean
    public ApplicationListener applicationListener() {
        return event -> {
            if (event instanceof PayloadApplicationEvent) {
                PayloadApplicationEvent payloadApplicationEvent = (PayloadApplicationEvent) event;
                System.out.println("接收到了一个事件:" + payloadApplicationEvent.getPayload());
            }
        };
    }
}

Main:发布消息

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        context.publishEvent("abc");
    }

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

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

相关文章

多元回归预测 | Matlab鲸鱼算法(WOA)优化极限梯度提升树XGBoost回归预测,WOA-XGBoost回归预测模型,多变量输入模型

文章目录 效果一览文章概述部分源码参考资料效果一览 文章概述 多元回归预测 | Matlab鲸鱼算法(WOA)优化极限梯度提升树XGBoost回归预测,WOA-XGBoost回归预测模型,多变量输入模型 评价指标包括:MAE、RMSE和R2等,代码质量极高,方便学习和替换数据。要求2018版本及以上。 部分源…

css实现九宫格有边框,最外层四周无边框

1.先设置9个div&#xff0c;如下&#xff1a; <div class"wrapper"><div class"cell"></div><div class"cell"></div><div class"cell"></div><div class"cell"></div&…

【MySQL】连接 MySQL使用二进制方式连接和脚本连接,修改密码,增加新用户,显示命令

作者简介&#xff1a; 辭七七&#xff0c;目前大一&#xff0c;正在学习C/C&#xff0c;Java&#xff0c;Python等 作者主页&#xff1a; 七七的个人主页 文章收录专栏&#xff1a; 七七的闲谈 欢迎大家点赞 &#x1f44d; 收藏 ⭐ 加关注哦&#xff01;&#x1f496;&#x1f…

RocketMQ5.0--消息发送

RocketMQ5.0–消息发送 一、消息 // 消息所属topic private String topic; // 消息Flag&#xff08;RocketMQ不作处理&#xff09;&#xff0c;即&#xff1a;用户处理 private int flag; // 扩展属性 private Map<String, String> properties; // 消息体 private byte…

Pandas+Pyecharts | 北京近五年历史天气数据可视化

文章目录 &#x1f3f3;️‍&#x1f308; 1. 导入模块&#x1f3f3;️‍&#x1f308; 2. Pandas数据处理2.1 读取数据2.2 处理最低气温最高气温数据2.3 处理日期数据2.4 处理风力风向数据 &#x1f3f3;️‍&#x1f308; 3. Pyecharts数据可视化3.1 2018-2022年历史温度分布…

漏洞复现 || H3C iMC 存在远程命令执行

免责声明 技术文章仅供参考,任何个人和组织使用网络应当遵守宪法法律,遵守公共秩序,尊重社会公德,不得利用网络从事危害国家安全、荣誉和利益,未经授权请勿利用文章中的技术资料对任何计算机系统进行入侵操作。利用此文所提供的信息而造成的直接或间接后果和损失,均由使…

软件的验收测试应该怎么正确实施?

验收测试的主要目的是为了确定软件系统是否满足客户或最终用户的需求和期望&#xff0c;同时确保软件产品的质量标准达到预期。验收测试还可以提供客户和最终用户关于软件系统质量的反馈和建议&#xff0c;以便软件开发团队能够更好地改进和优化软件产品&#xff0c;那软件的验…

【QT】QtXlsx安装使用

QtXlsx库 QtXlsx介绍QtXlsx Qt配置简单使用示例 QtXlsx介绍 QtXlsx是一个可以读取和写入Excel文件的库。它不需要Microsoft Excel&#xff0c;可以在Qt5支持的任何平台上使用。 这里一定是需要QT5支持的。 生成一个新的 .xlsx 文件从现有的 .xlsx 文件中提取数据编辑现有的 .x…

Linux常用指令(下)

目录 一&#xff1a;Linux基础指令 查看联机手册 文本查看相关 时间相关 查找相关 打包和压缩相关 查看Linux版本和体系 其它指令和热键 二&#xff1a;重定向 输入重定向 输出重定向 三&#xff1a;管道 一&#xff1a;Linux基础指令 查看联机手册 Linux的命令有…

ADS笔记,新旧两组仿真数据进行绘图和列表对比

做个笔记&#xff0c;以防遗忘 ADS版本&#xff1a;2023 原理图器件参数的不同&#xff0c;怎么进行对比观看&#xff0c;操作如下 目录 一、数据绘图对比二、数据列表对比 一、数据绘图对比 选择Simulation Setting 然后修改原理图器件的参数&#xff0c;再次重复之前的操作…

SpringBoot2+Vue2实战(十三)用户前台页面设计与实现

Front.vue <template><div><!--头部--><div style"display: flex; height: 60px;line-height: 60px;border-bottom: 1px solid #ccc"><div style"width: 300px;display: flex;padding-left: 30px"><div style"widt…

CENTOS上的网络安全工具(二十七)SPARK+NetSA Security Tools容器化部署(3)

上回说到在我们搭好的YAF3环境上使用yaf处理pcap文件得到silk flow&#xff0c;再使用super mediator工具转为ipfix&#xff0c;继而在spark中导入mothra&#xff0c;就可以开始数据分析了。然而在我们粗粗一用之下&#xff0c;却发现DPI信息在ipfix文件中找不到&#xff0c;到…

【Excel】csv乱码

原因 CSV用UTF-8编码 Excel用ANSI编码 解决 1 创建一个新的Excel 2 数据 > 从文本/CSV 3 选择文件 4 选择 文件原始格式 和 分隔符 &#xff08;根据自己文件进行选择&#xff0c;如果不知道编码&#xff0c;可以一个一个的试&#xff0c;直到不出现乱码&#xff09;

【Go|第5期】Lorca无法正常运行的解决方案

日期&#xff1a;2023年7月5日 作者&#xff1a;Commas 签名&#xff1a;(ง •_•)ง 积跬步以致千里,积小流以成江海…… 注释&#xff1a;如果您觉得有所帮助&#xff0c;帮忙点个赞&#xff0c;也可以关注我&#xff0c;我们一起成长&#xff1b;如果有不对的地方&#xff…

奇怪的SQL问题+1

我的 VIP 用户又抛给我一个 SQL 问题&#xff0c;我很激动&#xff0c;因为素材又来了&#xff1a; 我一看&#xff0c;这个表没什么花头&#xff0c;不就是没设置主键吗&#xff0c;MySQL 会默认生成一个主键&#xff0c;这跟 delete 不掉数据好像也没啥关系。 然后他说&…

事件监听及DOM操作

1.页面内容实现 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>常见事件案例</title> </head> <body><img id"light" src"img/off.gif"> <br><…

红黑树的介绍

红黑树 1.红黑树的概念2. 红黑树的性质3. 红黑树的结点定义4. 红黑树的插入操作情况一: cur为红&#xff0c;p为红&#xff0c;g为黑&#xff0c;u存在且为红情况二: cur为红&#xff0c;p为红&#xff0c;g为黑&#xff0c;u不存在/u存在且为黑情况三: cur为红&#xff0c;p为…

Distributional Graphormer:从分子结构预测到平衡分布预测

编者按&#xff1a;近年来&#xff0c;深度学习技术在分子微观结构预测中取得了巨大的进展。然而&#xff0c;分子的宏观属性和功能往往取决于分子结构在平衡态下的分布&#xff0c;仅了解分子的微观结构还远远不够。在传统的统计力学中&#xff0c;分子动力学模拟或增强采样等…

【计算机视觉 | 目标检测】arxiv 计算机视觉关于目标检测的学术速递(7 月 6 日论文合集)

文章目录 一、检测相关(16篇)1.1 Large-scale Detection of Marine Debris in Coastal Areas with Sentinel-21.2 Unbalanced Optimal Transport: A Unified Framework for Object Detection1.3 Detecting Images Generated by Deep Diffusion Models using their Local Intrin…

Oracle单行函数(字符,数值,日期,转换)

Oracle单行函数&#xff08;字符&#xff0c;数值&#xff0c;日期&#xff0c;转换&#xff09; 前言 1、字符函数 1.1大小写转换函数 1.2连接字符串X和concat(X,Y) 1.3ASCII码与字符转换 1.4返回字符串索引位置&#xff1a;instr(x,str) 1.5返回字符串长度&#xff1a;length…