前言
在之前的文章中,我们已经对Spring源码中的一些核心概念进行了分析。由于篇幅限制,我们并没有详细解释ApplicationContext类所继承的父接口及其作用。因此,本文将单独为ApplicationContext进行详细说明,包括其继承的父接口及其作用。
ApplicationContext父接口
MessageSource
大家应该都比较熟悉MessageSource,它用于国际化,许多项目都会使用它。使用MessageSource的基本步骤如下:
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
String message = applicationContext.getMessage("test", null, new Locale("en"));
System.out.println(message);
你需要在resources路径下创建相应的语言文件。例如,在本文的代码示例中,我们使用了“en”语言,因此需要创建messages_en.properties文件,其内容如下:
test=b
这样,当我们获取“test”语言时,就会得到“b”。
ResourcePatternResolver
ResourcePatternResolver主要用于获取资源,即资源加载,可以加载某个文件的内容。具体步骤如下:
// 创建一个Spring容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
// String message = applicationContext.getMessage("test", null, new Locale("en"));
// System.out.println(message);
Resource resource = applicationContext.getResource("classpath:spring.properties");
System.out.println(resource.contentLength());
除此之外,ResourcePatternResolver还有其他用法,例如:
// 创建一个Spring容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
// String message = applicationContext.getMessage("test", null, new Locale("en"));
// System.out.println(message);
Resource resource = applicationContext.getResource("https://www.baidu.com");
System.out.println(resource.contentLength());
System.out.println(resource.getURL());
//还可以获取多个资源
Resource[] resources = applicationContext.getResources("classpath:com/xiaoyu/*.class");
Arrays.stream(resources).forEach(System.out::println);
以上只是简单的示例,具体使用方法还需根据实际情况进行调整。
EnvironmentCapable
获取运行时环境可以使用ApplicationContext的getEnvironment方法,具体用法如下:
// 创建一个Spring容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
applicationContext.getEnvironment().getPropertySources().forEach(System.out::println);
System.out.println("================");
applicationContext.getEnvironment().getSystemEnvironment().forEach((k, v) -> System.out.println(k + " : " + v));
System.out.println("================");
applicationContext.getEnvironment().getSystemProperties().forEach((k, v) -> System.out.println(k + " : " + v));
System.out.println("================");
System.out.println(applicationContext.getEnvironment().getProperty("sun.jnu.encoding"));
System.out.println(applicationContext.getEnvironment().getProperty("xiaoyu"));
@PropertySource("classpath:spring.properties")
注意,可以使用@PropertySource注解将spring.properties添加到运行时环境,然后通过getProperty方法去获取。
ApplicationEventPublisher
ApplicationEventPublisher是一个事件发布器,我们可以通过ApplicationContext来发布一个相应的事件,具体步骤如下:
// 创建一个Spring容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
//发布自己的事件
applica