第一步,我们先来看这个接口的内部结构,了解别人的内部,知己知彼,百战不殆:
这个接口的扩展功能主要体现在它继承的四个接口上:
- MessageSource:国际化功能
- ResourcePatternResolver: 资源访问功能
- ApplicationEventPublisher: Spring事件发布者功能
- EnvironmentCapable:提供当前系统环境 Environment 组件功能
国际化功能演示
查看对应的方法:
准备翻译资源信息:
--------messages_en.properties
hi=Hello
--------messages_ja.properties
hi=こんにちは
---------messages_zh.properties
hi=你好
使用context容器对象,通过getMessage方法。根据key进行翻译:
1
2
3
4
5
6
7
8
|
//处理国际化资源(国际化能力) //中文(参数:key,变化的信息,翻译的类型) //根据key找到不同语言的翻译结果 System.out.println(context.getMessage( "hi" , null , Locale.CHINA)); //英文 System.out.println(context.getMessage( "hi" , null , Locale.ENGLISH)); //日文 System.out.println(context.getMessage( "hi" , null , Locale.JAPANESE)); |
资源访问功能演示:
查看对应的方法:
第一个是根据路径获取多个资源,第二个是根据路径获取单个资源
1
2
3
4
5
6
7
|
//根据磁盘的路径获取单个资源 context.getResources( "classpath:spring.properties" ); //获取多个资源 Resource[] resources = context.getResources( "classpath*:META-INF/spring.factories" ); for (Resource resource : resources) { System.out.println(resource); } |
提供当前系统环境 Environment 组件功能演示:
1
2
|
System.out.println(context.getEnvironment().getProperty( "java_home" )); System.out.println(context.getEnvironment().getProperty( "server.port" )); |
作用:获取配置信息
Spring事件发布者功能演示:
定义事件:
1
2
3
4
5
6
7
|
//用户已注册事件 public class UserRegisteredEvent extends ApplicationEvent { // source 事件的事件源 public UserRegisteredEvent(Object source) { super (source); } } |
发布事件:
1
|
context.publishEvent( new UserRegisteredEvent(context)); |
接收事件(监听器):
1
2
3
4
5
6
7
8
9
10
|
@Component public class Component2 { private static final Logger log = LoggerFactory.getLogger(Component2. class ); @EventListener //发的是什么事件,就用什么事件来接收 public void aaa(UserRegisteredEvent event) { log.debug( "{}" , event); log.debug( "发送短信" ); } } |
实现用户注册与发送短信之间的解耦:
1
2
3
4
5
6
7
8
9
10
|
@Component public class Component1 { private static final Logger log = LoggerFactory.getLogger(Component1. class ); @Autowired private ApplicationEventPublisher context; public void register() { log.debug( "用户注册" ); context.publishEvent( new UserRegisteredEvent( this )); } } |
测试:
1
|
context.getBean(Component1. class ).register(); |
重点:发布事件,使用监听器来获取事件,作用(实现组件之间的解耦)
总结:
- BeanFactory 与 ApplicationContext 并不仅仅是简单接口继承的关系, ApplicationContext 组合并扩展了 BeanFactory 的功能
- 又新学一种代码之间解耦途径(发布事件)
到此这篇关于Spring ApplicationContext接口功能详细介绍的文章就介绍到这了,更多相关Spring ApplicationContext接口内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/qq_61313896/article/details/128745712