目录
Spring Expression Language(SpEL)
Spring Context 模块详解
Spring Context 模块是 Spring 框架的一个重要模块,它建立在 Core 和 Beans 模块的基础之上,提供了更高级的特性,如国际化(I18N)、事件传播、资源管理、依赖注入(DI)、生命周期管理以及对 Java EE 特性的支持。它扩展了 BeanFactory
,为应用程序提供了丰富的上下文环境。
1. 什么是 Spring Context?
ApplicationContext
是 Spring Context 模块的核心接口,它是 Spring IoC 容器的高级接口,扩展了基础的 BeanFactory
功能,不仅支持 Bean 的创建和管理,还提供了企业级的特性,例如:
- 国际化(国际化消息)
- 事件传播(监听和发布事件)
- 资源访问(文件、URL、classpath 等)
- 自动装配(基于注解和自动检测)
通过 ApplicationContext
,Spring 应用程序能够管理 Bean 的生命周期、依赖关系、配置和运行时行为。
2. ApplicationContext 的主要实现
Spring 提供了多种 ApplicationContext
的实现,适用于不同的应用场景:
ClassPathXmlApplicationContext
:从类路径下的 XML 配置文件中加载上下文。FileSystemXmlApplicationContext
:从文件系统中的 XML 配置文件中加载上下文。AnnotationConfigApplicationContext
:基于注解的配置上下文,通常用于基于 Java 配置的应用程序。WebApplicationContext
:用于 Web 应用的上下文,实现了ApplicationContext
,并集成了 Servlet 环境。
3. 国际化支持
ApplicationContext
提供了对国际化(I18N)的支持,允许开发者根据用户的区域设置信息提供不同语言的消息。Spring 通过 MessageSource
接口实现了对国际化消息的管理,可以在配置文件中或通过 Java 类来定义国际化消息。
国际化消息文件
国际化消息通常存储在 .properties
文件中,不同语言的消息文件名称会有所区别,例如:
messages.properties
:默认语言messages_en.properties
:英文messages_fr.properties
:法语
使用 MessageSource
配置 MessageSource
来加载国际化消息:
XML 配置:
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
Java 配置:
@Configuration
public class AppConfig {
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource source = new ResourceBundleMessageSource();
source.setBasename("messages");
return source;
}
}
使用国际化消息:
@Autowired
private MessageSource messageSource;
public void printMessage(Locale locale) {
String message = messageSource.getMessage("greeting", null, locale);
System.out.println(message);
}
通过 Locale
参数,开发者可以获取基于不同语言环境的消息。
4. 事件处理机制
Spring 的事件机制使得应用程序中的组件之间可以通过发布和监听事件进行松散耦合的通信。Spring 提供了简单且强大的事件处理机制,基于 Observer Design Pattern(观察者模式)。
核心接口与类:
ApplicationEvent
:所有事件类的父类,开发者可以自定义事件,继承自该类。ApplicationListener
:事件监听器接口,开发者可以实现该接口来处理事件。ApplicationEventPublisher
:事件发布接口,Spring IoC 容器实现了该接口,开发者可以通过它发布事件。
自定义事件:
public class CustomEvent extends ApplicationEvent {
public CustomEvent(Object source) {
super(source);
}
}
自定义监听器:
@Component
public class CustomEventListener implements ApplicationListener<CustomEvent> {
@Override
public void onApplicationEvent(CustomEvent event) {
System.out.println("Received custom event: " + event.getSource());
}
}
发布事件:
@Component
public class EventPublisher {
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
public void publishEvent() {
CustomEvent customEvent = new CustomEvent(this);
applicationEventPublisher.publishEvent(customEvent);
}
}