Spring ApplicationContext源码详解(详细注释版)
1. ApplicationContext接口源码
/*
* ApplicationContext接口是Spring框架的核心接口之一
* 代表Spring IoC容器,提供了配置、创建和管理Bean的完整功能
* 是BeanFactory的扩展,提供了更多企业级功能
*
* ApplicationContext的作用:
* 1. 统一的配置管理入口
* 2. Bean的生命周期管理
* 3. 国际化支持
* 4. 事件发布机制
* 5. 资源加载能力
* 6. AOP支持
*
* 注意事项:
* - ApplicationContext是BeanFactory的超集
* - 提供了更多企业级特性
* - 是Spring应用的中心接口
*/
package org.springframework.context;
import java.io.Closeable;
import java.util.Locale;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.HierarchicalBeanFactory;
import org.springframework.core.env.EnvironmentCapable;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.lang.Nullable;
/**
* 为应用程序提供配置的中央接口
*
* ApplicationContext在BeanFactory的基础上增加了:
* 1. 应用层特定的上下文,如Web应用上下文
* 2. 检测在上下文中定义的beans
* 3. 加载资源文件
* 4. 发布事件给注册的监听器
* 5. 解析消息,支持国际化
* 6. 继承父上下文,实现层次化配置
*
* ApplicationContext的典型实现:
* - ClassPathXmlApplicationContext: 从类路径加载XML配置
* - FileSystemXmlApplicationContext: 从文件系统加载XML配置
* - AnnotationConfigApplicationContext: 基于注解的配置
* - WebApplicationContext: Web应用上下文
*
* 执行时机:
* 1. 上下文创建和刷新
* 2. Bean定义加载
* 3. Bean实例化和初始化
* 4. 应用程序运行
* 5. 上下文关闭
*/
public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,
MessageSource, ApplicationEventPublisher, ResourcePatternResolver, Closeable {
/**
* 获取此应用程序上下文的唯一ID
*
* @return 应用程序上下文的唯一ID
*
* 使用场景:
* - 上下文标识
* - 日志记录
* - 分布式系统中的上下文识别
*/
@Nullable
String getId();
/**
* 返回此应用程序上下文的名称
*
* @return 应用程序上下文的名称
*
* 使用场景:
* - 用户友好的上下文标识
* - 配置显示
* - 管理界面展示
*/
String getApplicationName();
/**
* 返回此上下文的显示名称
*
* @return 此上下文的显示名称
*
* 使用场景:
* - 日志输出
* - 错误消息
* - 用户界面显示
*/
String getDisplayName();
/**
* 返回此上下文首次加载的时间
*
* @return 此上下文首次加载的时间(毫秒)
*
* 使用场景:
* - 性能监控
* - 启动时间统计
* - 系统诊断
*/
long getStartupDate();
/**
* 返回此应用程序上下文的父上下文
*
* @return 父上下文,如果没有父上下文则返回null
*
* 使用场景:
* - 层次化配置管理
* - Bean查找的继承机制
* - 配置隔离
*/
@Nullable
ApplicationContext getParent();
/**
* 为此应用程序上下文获取AutowireCapableBeanFactory
*
* @return 此上下文的AutowireCapableBeanFactory
* @throws IllegalStateException 如果上下文不支持此操作
*
* 使用场景:
* - 手动装配Bean
* - 集成第三方框架
* - 动态Bean创建
*/
AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException;
}
2. ConfigurableApplicationContext接口
/*
* ConfigurableApplicationContext接口扩展了ApplicationContext
* 提供了配置和生命周期管理的方法
* 是ApplicationContext实现类的主要接口
*/
package org.springframework.context;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.core.env.ConfigurableEnvironment;
/**
* 可配置的应用程序上下文接口
* 提供了对ApplicationContext的配置和生命周期管理能力
*
* 主要功能:
* 1. 上下文生命周期管理(刷新、关闭)
* 2. 配置管理(环境、BeanFactory后处理器)
* 3. 事件系统配置
* 4. 启动阶段管理
*
* 执行顺序:
* 1. setId() - 设置ID
* 2. setEnvironment() - 设置环境
* 3. addBeanFactoryPostProcessor() - 添加BeanFactory后处理器
* 4. addApplicationListener() - 添加监听器
* 5. refresh() - 刷新上下文
* 6. close() - 关闭上下文
*/
public interface ConfigurableApplicationContext extends ApplicationContext, Lifecycle, Closeable {
/**
* 设置此应用程序上下文的ID
*
* @param id 应用程序上下文的ID
*
* 使用场景:
* - 自定义上下文标识
* - 分布式系统中的上下文管理
* - 配置管理
*/
void setId(String id);
/**
* 设置此应用程序上下文的父上下文
*
* @param parent 父上下文
*
* 使用场景:
* - 层次化上下文配置
* - 配置继承
* - Bean查找的层次结构
*/
void setParent(@Nullable ApplicationContext parent);
/**
* 设置此应用程序上下文的Environment
*
* @param environment Environment实例
*
* 使用场景:
* - 自定义环境配置
* - 多环境支持
* - 配置属性管理
*/
void setEnvironment(ConfigurableEnvironment environment);
/**
* 返回此应用程序上下文的内部BeanFactory
*
* @return 内部BeanFactory
*
* 使用场景:
* - 直接访问BeanFactory
* - 高级配置操作
* - 自定义Bean管理
*/
ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;
/**
* 添加新的BeanFactoryPostProcessor
*
* @param beanFactoryPostProcessor 要注册的BeanFactoryPostProcessor
*
* 使用场景:
* - 动态添加配置处理器
* - 自定义Bean定义处理
* - 条件化配置
*/
void addBeanFactoryPostProcessor(BeanFactoryPostProcessor beanFactoryPostProcessor);
/**
* 添加新的ApplicationListener
*
* @param listener 要注册的ApplicationListener
*
* 使用场景:
* - 动态添加事件监听器
* - 运行时事件处理
* - 插件化架构
*/
void addApplicationListener(ApplicationListener<?> listener);
/**
* 指定刷新和关闭时是否注册关闭钩子
*
* @param register 是否注册关闭钩子
*
* 使用场景:
* - JVM关闭时的资源清理
* - 优雅关闭
* - 自动资源管理
*/
void setRegisterShutdownHook(boolean register);
/**
* 注册JVM关闭钩子,确保在JVM关闭时优雅地关闭此上下文
*
* 使用场景:
* - 自动资源清理
* - 优雅关闭应用
* - 防止资源泄露
*/
void registerShutdownHook();
/**
* 关闭此应用程序上下文,释放所有资源和锁
*
* 使用场景:
* - 应用关闭
* - 资源清理
* - 测试环境清理
*/
@Override
void close();
/**
* 判断此应用程序上下文是否处于激活状态
*
* @return 如果上下文处于激活状态返回true
*
* 使用场景:
* - 状态检查
* - 条件化操作
* - 健康检查
*/
boolean isActive();
/**
* 加载或刷新配置的持久化表示
*
* 使用场景:
* - 初始化应用上下文
* - 重新加载配置
* - 动态配置更新
*/
void refresh() throws BeansException, IllegalStateException;
}
3. AbstractApplicationContext核心实现
/*
* AbstractApplicationContext是ApplicationContext的主要抽象实现
* 提供了ApplicationContext的核心功能实现
*/
public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext {
// 日志记录器
protected final Log logger = LogFactory.getLog(getClass());
// 上下文ID
private String id = ObjectUtils.identityToString(this);
// 应用名称
private String applicationName = "";
// 显示名称
private String displayName = ObjectUtils.identityToString(this);
// 父上下文
@Nullable
private ApplicationContext parent;
// 环境
@Nullable
private ConfigurableEnvironment environment;
// BeanFactory后处理器列表
private final List<BeanFactoryPostProcessor> beanFactoryPostProcessors = new ArrayList<>();
// 启动日期
private long startupDate;
// 关闭状态标志
private final AtomicBoolean closed = new AtomicBoolean();
// 激活状态标志
private final AtomicBoolean active = new AtomicBoolean();
// 启动关闭锁
private final Object startupShutdownMonitor = new Object();
// 应用事件广播器
@Nullable
private ApplicationEventMulticaster applicationEventMulticaster;
// 应用监听器列表
private final Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet<>();
// 注册的监听器列表
@Nullable
private Set<ApplicationListener<?>> registeredListeners;
// 生命周期处理器
@Nullable
private LifecycleProcessor lifecycleProcessor;
// 消息源
@Nullable
private MessageSource messageSource;
// 内部BeanFactory
@Nullable
protected ConfigurableListableBeanFactory beanFactory;
// 资源模式解析器
private ResourcePatternResolver resourcePatternResolver;
// 关闭钩子
@Nullable
private Thread shutdownHook;
// 虚拟机关闭钩子是否已注册
private volatile boolean shutdownHookRegistered = false;
/**
* 构造方法
*/
public AbstractApplicationContext() {
this.resourcePatternResolver = getResourcePatternResolver();
}
/**
* 带父上下文的构造方法
*/
public AbstractApplicationContext(@Nullable ApplicationContext parent) {
this();
setParent(parent);
}
/**
* 获取资源模式解析器
*/
protected ResourcePatternResolver getResourcePatternResolver() {
return new PathMatchingResourcePatternResolver(this);
}
/**
* 设置父上下文
*/
@Override
public void setParent(@Nullable ApplicationContext parent) {
this.parent = parent;
if (parent != null) {
Environment parentEnvironment = parent.getEnvironment();
if (parentEnvironment instanceof ConfigurableEnvironment) {
getEnvironment().merge((ConfigurableEnvironment) parentEnvironment);
}
}
}
/**
* 获取父上下文
*/
@Override
@Nullable
public ApplicationContext getParent() {
return this.parent;
}
/**
* 刷新上下文的核心方法
* 这是ApplicationContext初始化的入口点
*/
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// 准备刷新上下文
prepareRefresh();
// 告诉子类刷新内部Bean工厂
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 准备Bean工厂用于在此上下文中使用
prepareBeanFactory(beanFactory);
try {
// 允许上下文子类对Bean工厂进行后处理
postProcessBeanFactory(beanFactory);
// 调用BeanFactoryPostProcessor
invokeBeanFactoryPostProcessors(beanFactory);
// 注册BeanPostProcessor
registerBeanPostProcessors(beanFactory);
// 初始化消息源
initMessageSource();
// 初始化应用事件广播器
initApplicationEventMulticaster();
// 初始化其他特殊Bean
onRefresh();
// 检查并注册监听器Bean
registerListeners();
// 实例化所有剩余的(非延迟初始化的)单例Bean
finishBeanFactoryInitialization(beanFactory);
// 最后一步:发布相应的事件
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// 销毁已经创建的单例Bean以避免悬空资源
destroyBeans();
// 重置'active'标志
cancelRefresh(ex);
// 传播异常到调用者
throw ex;
}
finally {
// 重置Spring核心中的常见内省缓存
resetCommonCaches();
}
}
}
/**
* 准备刷新上下文
*/
protected void prepareRefresh() {
// 切换到激活状态
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
if (logger.isDebugEnabled()) {
if (logger.isTraceEnabled()) {
logger.trace("Refreshing " + this);
}
else {
logger.debug("Refreshing " + getDisplayName());
}
}
// 初始化属性源中的任何占位符
initPropertySources();
// 验证标记为必需的属性是否可解析
getEnvironment().validateRequiredProperties();
// 存储预刷新的应用监听器...
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
// 重置本地应用监听器到预刷新状态
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// 允许收集早期的应用事件,一旦广播器可用就发布...
this.earlyApplicationEvents = new LinkedHashSet<>();
}
/**
* 获取新的Bean工厂
*/
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
}
/**
* 准备Bean工厂
*/
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// 设置Bean工厂的类加载器
beanFactory.setBeanClassLoader(getClassLoader());
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// 配置Bean工厂的后处理器
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
// 注册特殊的可解析依赖项
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// 注册早期的Bean后处理器,用于检测内部Bean
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// 检测LoadTimeWeaver并准备进行织入(如果找到)
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// 为类型匹配设置临时类加载器
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// 注册默认的环境Bean
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
}
/**
* 刷新Bean工厂
* 抽象方法,由子类实现
*/
protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;
/**
* 获取Bean工厂
* 抽象方法,由子类实现
*/
@Override
public abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;
/**
* 允许上下文子类对Bean工厂进行后处理
*/
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// 默认实现为空,子类可以重写
}
/**
* 调用BeanFactoryPostProcessor
*/
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
}
/**
* 注册BeanPostProcessor
*/
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
/**
* 初始化消息源
*/
protected void initMessageSource() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
// 使MessageSource知道父MessageSource
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
if (hms.getParentMessageSource() == null) {
// 仅在父MessageSource尚未设置时设置父MessageSource
hms.setParentMessageSource(getInternalParentMessageSource());
}
}
if (logger.isTraceEnabled()) {
logger.trace("Using MessageSource [" + this.messageSource + "]");
}
}
else {
// 使用空MessageSource以便能够接受getMessage调用
DelegatingMessageSource dms = new DelegatingMessageSource();
dms.setParentMessageSource(getInternalParentMessageSource());
this.messageSource = dms;
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
if (logger.isTraceEnabled()) {
logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
}
}
}
/**
* 初始化应用事件广播器
*/
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isTraceEnabled()) {
logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
else {
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
if (logger.isTraceEnabled()) {
logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
"[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
}
}
}
/**
* 子类可以重写此方法以添加自定义上下文刷新逻辑
*/
protected void onRefresh() throws BeansException {
// 默认实现为空,子类可以重写
}
/**
* 注册监听器
*/
protected void registerListeners() {
// 注册静态指定的监听器
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// 通过后处理器注册的单例Bean的监听器
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// 发布早期的应用事件(现在多播器已可用)
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (earlyEventsToProcess != null) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
/**
* 完成Bean工厂初始化
*/
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// 初始化转换服务
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}
// 如果没有提供属性编辑器注册器,则注册默认的嵌入值解析器
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// 初始化LoadTimeWeaverAware Bean
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// 停止使用临时类加载器进行类型匹配
beanFactory.setTempClassLoader(null);
// 冻结所有Bean定义元数据,Bean定义现在不应该再被修改或后处理
beanFactory.freezeConfiguration();
// 实例化所有剩余的(非延迟初始化的)单例
beanFactory.preInstantiateSingletons();
}
/**
* 完成刷新
*/
protected void finishRefresh() {
// 清除上下文级别的资源缓存
clearResourceCaches();
// 初始化生命周期处理器
initLifecycleProcessor();
// 首先将刷新传播到生命周期处理器
getLifecycleProcessor().onRefresh();
// 发布最终的事件
publishEvent(new ContextRefreshedEvent(this));
// 参与LiveBeansView MBean(如果处于活动状态)
LiveBeansView.registerApplicationContext(this);
}
/**
* 初始化生命周期处理器
*/
protected void initLifecycleProcessor() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
this.lifecycleProcessor =
beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
if (logger.isTraceEnabled()) {
logger.trace("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
}
}
else {
DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
defaultProcessor.setBeanFactory(beanFactory);
this.lifecycleProcessor = defaultProcessor;
beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
if (logger.isTraceEnabled()) {
logger.trace("No '" + LIFECYCLE_PROCESSOR_BEAN_NAME + "' bean, using " +
"[" + this.lifecycleProcessor.getClass().getSimpleName() + "]");
}
}
}
/**
* 获取生命周期处理器
*/
@Override
public LifecycleProcessor getLifecycleProcessor() throws IllegalStateException {
if (this.lifecycleProcessor == null) {
throw new IllegalStateException("LifecycleProcessor not initialized - " +
"call 'refresh' before invoking lifecycle methods via the context: " + this);
}
return this.lifecycleProcessor;
}
/**
* 获取内部父消息源
*/
@Nullable
protected MessageSource getInternalParentMessageSource() {
return (getParent() instanceof ConfigurableApplicationContext ?
((ConfigurableApplicationContext) getParent()).getInternalParentMessageSource() : getParent());
}
/**
* 获取应用事件广播器
*/
@Override
public ApplicationEventMulticaster getApplicationEventMulticaster() throws IllegalStateException {
if (this.applicationEventMulticaster == null) {
throw new IllegalStateException("ApplicationEventMulticaster not initialized - " +
"call 'refresh' before multicasting events via the context: " + this);
}
return this.applicationEventMulticaster;
}
/**
* 获取应用监听器
*/
public Collection<ApplicationListener<?>> getApplicationListeners() {
return this.applicationListeners;
}
/**
* 发布事件
*/
@Override
public void publishEvent(ApplicationEvent event) {
publishEvent(event, null);
}
/**
* 发布事件的具体实现
*/
protected void publishEvent(Object event, @Nullable ResolvableType eventType) {
Assert.notNull(event, "Event must not be null");
// 装饰事件为ApplicationEvent(如果需要)
ApplicationEvent applicationEvent;
if (event instanceof ApplicationEvent) {
applicationEvent = (ApplicationEvent) event;
}
else {
applicationEvent = new PayloadApplicationEvent<>(this, event);
if (eventType == null) {
eventType = ((PayloadApplicationEvent<?>) applicationEvent).getResolvableType();
}
}
// 多播早期的应用事件
if (this.earlyApplicationEvents != null) {
this.earlyApplicationEvents.add(applicationEvent);
}
else {
getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);
}
// 如果存在父上下文,则发布到父上下文
if (this.parent != null) {
if (this.parent instanceof AbstractApplicationContext) {
((AbstractApplicationContext) this.parent).publishEvent(event, eventType);
}
else {
this.parent.publishEvent(event);
}
}
}
/**
* 关闭上下文
*/
@Override
public void close() {
synchronized (this.startupShutdownMonitor) {
doClose();
// 如果已注册关闭钩子,则移除它
if (this.shutdownHook != null) {
try {
Runtime.getRuntime().removeShutdownHook(this.shutdownHook);
}
catch (IllegalStateException ex) {
// 忽略 - VM正在关闭
}
}
}
}
/**
* 执行关闭操作
*/
protected void doClose() {
// 检查是否已经关闭(避免重复关闭)
if (this.active.get() && this.closed.compareAndSet(false, true)) {
if (logger.isDebugEnabled()) {
logger.debug("Closing " + this);
}
LiveBeansView.unregisterApplicationContext(this);
try {
// 发布关闭事件
publishEvent(new ContextClosedEvent(this));
}
catch (Throwable ex) {
logger.warn("Exception thrown from ApplicationListener handling ContextClosedEvent", ex);
}
// 停止生命周期Bean
if (this.lifecycleProcessor != null) {
try {
this.lifecycleProcessor.onClose();
}
catch (Throwable ex) {
logger.warn("Exception thrown from LifecycleProcessor on context close", ex);
}
}
// 销毁所有缓存的单例Bean
destroyBeans();
// 关闭状态:我们不再激活...
if (this.active.get()) {
this.active.set(false);
}
}
}
/**
* 销毁Beans
*/
protected void destroyBeans() {
getBeanFactory().destroySingletons();
}
/**
* 取消刷新
*/
protected void cancelRefresh(BeansException ex) {
this.active.set(false);
}
/**
* 重置常见缓存
*/
protected void resetCommonCaches() {
ReflectionUtils.clearCache();
AnnotationUtils.clearCache();
ResolvableType.clearCache();
CachedIntrospectionResults.clearClassLoader(getClassLoader());
}
/**
* 获取Bean
*/
@Override
public Object getBean(String name) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBean(name);
}
/**
* 获取Bean(带类型)
*/
@Override
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBean(name, requiredType);
}
/**
* 获取Bean(带参数)
*/
@Override
public Object getBean(String name, Object... args) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBean(name, args);
}
/**
* 获取Bean(按类型)
*/
@Override
public <T> T getBean(Class<T> requiredType) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBean(requiredType);
}
/**
* 获取Bean(按类型和参数)
*/
@Override
public <T> T getBean(Class<T> requiredType, Object... args) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBean(requiredType, args);
}
/**
* 断言Bean工厂处于激活状态
*/
protected void assertBeanFactoryActive() {
if (!this.active.get()) {
if (this.closed.get()) {
throw new IllegalStateException(getDisplayName() + " has been closed already");
}
else {
throw new IllegalStateException(getDisplayName() + " has not been refreshed yet");
}
}
}
/**
* 获取Bean名称数组(按类型)
*/
@Override
public String[] getBeanNamesForType(@Nullable Class<?> type) {
assertBeanFactoryActive();
return getBeanFactory().getBeanNamesForType(type);
}
/**
* 获取Bean名称数组(按类型,包含非单例)
*/
@Override
public String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
assertBeanFactoryActive();
return getBeanFactory().getBeanNamesForType(type, includeNonSingletons, allowEagerInit);
}
/**
* 获取Beans(按类型)
*/
@Override
public <T> Map<String, T> getBeansOfType(@Nullable Class<T> type) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBeansOfType(type);
}
/**
* 获取Beans(按类型,包含非单例)
*/
@Override
public <T> Map<String, T> getBeansOfType(@Nullable Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBeansOfType(type, includeNonSingletons, allowEagerInit);
}
/**
* 获取Bean名称数组(按注解)
*/
@Override
public String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType) {
assertBeanFactoryActive();
return getBeanFactory().getBeanNamesForAnnotation(annotationType);
}
/**
* 获取Beans(按注解)
*/
@Override
public Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType)
throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBeansWithAnnotation(annotationType);
}
/**
* 查找注解在Bean上的注解
*/
@Override
@Nullable
public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType)
throws NoSuchBeanDefinitionException {
assertBeanFactoryActive();
return getBeanFactory().findAnnotationOnBean(beanName, annotationType);
}
/**
* 获取环境
*/
@Override
public ConfigurableEnvironment getEnvironment() {
if (this.environment == null) {
this.environment = createEnvironment();
}
return this.environment;
}
/**
* 创建环境
*/
protected ConfigurableEnvironment createEnvironment() {
return new StandardEnvironment();
}
/**
* 设置环境
*/
@Override
public void setEnvironment(ConfigurableEnvironment environment) {
this.environment = environment;
}
/**
* 获取资源
*/
@Override
public Resource getResource(String location) {
return this.resourcePatternResolver.getResource(location);
}
/**
* 获取资源数组
*/
@Override
public Resource[] getResources(String locationPattern) throws IOException {
return this.resourcePatternResolver.getResources(locationPattern);
}
/**
* 获取类加载器
*/
@Override
@Nullable
public ClassLoader getClassLoader() {
return this.resourcePatternResolver.getClassLoader();
}
/**
* 获取消息
*/
@Override
public String getMessage(String code, @Nullable Object[] args, @Nullable String defaultMessage, Locale locale) {
return getMessageSource().getMessage(code, args, defaultMessage, locale);
}
/**
* 获取消息
*/
@Override
public String getMessage(String code, @Nullable Object[] args, Locale locale) throws NoSuchMessageException {
return getMessageSource().getMessage(code, args, locale);
}
/**
* 获取消息
*/
@Override
public String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException {
return getMessageSource().getMessage(resolvable, locale);
}
/**
* 获取消息源
*/
private MessageSource getMessageSource() throws IllegalStateException {
if (this.messageSource == null) {
throw new IllegalStateException("MessageSource not initialized - " +
"call 'refresh' before accessing messages via the context: " + this);
}
return this.messageSource;
}
/**
* 启动
*/
@Override
public void start() {
getLifecycleProcessor().start();
publishEvent(new ContextStartedEvent(this));
}
/**
* 停止
*/
@Override
public void stop() {
getLifecycleProcessor().stop();
publishEvent(new ContextStoppedEvent(this));
}
/**
* 判断是否正在运行
*/
@Override
public boolean isRunning() {
return (this.lifecycleProcessor != null && this.lifecycleProcessor.isRunning());
}
/**
* 获取ID
*/
@Override
public String getId() {
return this.id;
}
/**
* 设置ID
*/
@Override
public void setId(String id) {
this.id = id;
}
/**
* 获取应用名称
*/
@Override
public String getApplicationName() {
return this.applicationName;
}
/**
* 设置应用名称
*/
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
/**
* 获取显示名称
*/
@Override
public String getDisplayName() {
return this.displayName;
}
/**
* 设置显示名称
*/
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
/**
* 获取启动日期
*/
@Override
public long getStartupDate() {
return this.startupDate;
}
/**
* 判断是否处于激活状态
*/
@Override
public boolean isActive() {
return this.active.get();
}
/**
* 判断是否已关闭
*/
public boolean isClosed() {
return this.closed.get();
}
/**
* 获取AutowireCapableBeanFactory
*/
@Override
public AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException {
return getBeanFactory();
}
/**
* 添加BeanFactoryPostProcessor
*/
@Override
public void addBeanFactoryPostProcessor(BeanFactoryPostProcessor postProcessor) {
Assert.notNull(postProcessor, "BeanFactoryPostProcessor must not be null");
this.beanFactoryPostProcessors.add(postProcessor);
}
/**
* 获取BeanFactoryPostProcessor列表
*/
public List<BeanFactoryPostProcessor> getBeanFactoryPostProcessors() {
return this.beanFactoryPostProcessors;
}
/**
* 添加应用监听器
*/
@Override
public void addApplicationListener(ApplicationListener<?> listener) {
Assert.notNull(listener, "ApplicationListener must not be null");
if (this.applicationEventMulticaster != null) {
this.applicationEventMulticaster.addApplicationListener(listener);
}
this.applicationListeners.add(listener);
}
/**
* 设置是否注册关闭钩子
*/
@Override
public void setRegisterShutdownHook(boolean registerShutdownHook) {
if (registerShutdownHook) {
registerShutdownHook();
}
else {
if (this.shutdownHook != null) {
try {
Runtime.getRuntime().removeShutdownHook(this.shutdownHook);
}
catch (IllegalStateException ex) {
// 忽略 - VM正在关闭
}
}
this.shutdownHook = null;
this.shutdownHookRegistered = false;
}
}
/**
* 注册关闭钩子
*/
@Override
public void registerShutdownHook() {
if (this.shutdownHook == null) {
// 如果JVM正在关闭,不要注册关闭钩子
if (this.active.get() && !this.closed.get()) {
// 仅在尚未注册时注册关闭钩子
if (!this.shutdownHookRegistered) {
try {
this.shutdownHook = new Thread(SHUTDOWN_HOOK_THREAD_NAME) {
@Override
public void run() {
synchronized (startupShutdownMonitor) {
doClose();
}
}
};
Runtime.getRuntime().addShutdownHook(this.shutdownHook);
this.shutdownHookRegistered = true;
}
catch (IllegalStateException ex) {
// 忽略 - VM正在关闭
}
}
}
}
}
}
4. 具体ApplicationContext实现
/*
* 具体的ApplicationContext实现类
*/
/**
* ClassPathXmlApplicationContext
* 从类路径加载XML配置文件的应用上下文
*/
public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContext {
// 配置文件路径
@Nullable
private Resource[] configResources;
/**
* 默认构造方法
*/
public ClassPathXmlApplicationContext() {
}
/**
* 带配置位置的构造方法
*/
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[] {configLocation}, true, null);
}
/**
* 带配置位置数组的构造方法
*/
public ClassPathXmlApplicationContext(String... configLocations) throws BeansException {
this(configLocations, true, null);
}
/**
* 带父上下文的构造方法
*/
public ClassPathXmlApplicationContext(String[] configLocations, @Nullable ApplicationContext parent)
throws BeansException {
this(configLocations, true, parent);
}
/**
* 完整构造方法
*/
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
/**
* 带资源配置的构造方法
*/
public ClassPathXmlApplicationContext(Resource... resources) throws BeansException {
this(true, null, resources);
}
/**
* 带父上下文和资源配置的构造方法
*/
public ClassPathXmlApplicationContext(boolean refresh, @Nullable ApplicationContext parent, Resource... resources)
throws BeansException {
super(parent);
this.configResources = resources;
if (refresh) {
refresh();
}
}
/**
* 获取资源配置
*/
@Override
@Nullable
protected Resource[] getConfigResources() {
return this.configResources;
}
/**
* 获取资源基路径
*/
@Override
protected String getResourceBasePath() {
return DEFAULT_RESOURCE_PATTERN;
}
}
/**
* FileSystemXmlApplicationContext
* 从文件系统加载XML配置文件的应用上下文
*/
public class FileSystemXmlApplicationContext extends AbstractXmlApplicationContext {
/**
* 默认构造方法
*/
public FileSystemXmlApplicationContext() {
}
/**
* 带配置位置的构造方法
*/
public FileSystemXmlApplicationContext(String configLocation) throws BeansException {
this(new String[] {configLocation}, true, null);
}
/**
* 带配置位置数组的构造方法
*/
public FileSystemXmlApplicationContext(String... configLocations) throws BeansException {
this(configLocations, true, null);
}
/**
* 带父上下文的构造方法
*/
public FileSystemXmlApplicationContext(String[] configLocations, ApplicationContext parent) throws BeansException {
this(configLocations, true, parent);
}
/**
* 完整构造方法
*/
public FileSystemXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
/**
* 获取资源基路径
*/
@Override
protected String getResourceBasePath() {
return FILE_URL_PREFIX;
}
}
/**
* AnnotationConfigApplicationContext
* 基于注解配置的应用上下文
*/
public class AnnotationConfigApplicationContext extends GenericApplicationContext implements AnnotationConfigRegistry {
// 注解Bean定义读取器
private final AnnotatedBeanDefinitionReader reader;
// 类路径Bean定义扫描器
private final ClassPathBeanDefinitionScanner scanner;
/**
* 默认构造方法
*/
public AnnotationConfigApplicationContext() {
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
/**
* 带组件类的构造方法
*/
public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
this();
register(componentClasses);
refresh();
}
/**
* 带包名的构造方法
*/
public AnnotationConfigApplicationContext(String... basePackages) {
this();
scan(basePackages);
refresh();
}
/**
* 注册组件类
*/
@Override
public void register(Class<?>... componentClasses) {
Assert.notEmpty(componentClasses, "At least one component class must be specified");
this.reader.register(componentClasses);
}
/**
* 扫描包
*/
@Override
public void scan(String... basePackages) {
Assert.notEmpty(basePackages, "At least one base package must be specified");
this.scanner.scan(basePackages);
}
/**
* 获取注解Bean定义读取器
*/
public AnnotatedBeanDefinitionReader getBeanDefinitionReader() {
return this.reader;
}
/**
* 获取类路径Bean定义扫描器
*/
public ClassPathBeanDefinitionScanner getScanner() {
return this.scanner;
}
/**
* 设置环境
*/
@Override
public void setEnvironment(ConfigurableEnvironment environment) {
super.setEnvironment(environment);
this.reader.setEnvironment(environment);
this.scanner.setEnvironment(environment);
}
/**
* 设置Bean名称生成器
*/
public void setBeanNameGenerator(BeanNameGenerator beanNameGenerator) {
this.reader.setBeanNameGenerator(beanNameGenerator);
this.scanner.setBeanNameGenerator(beanNameGenerator);
getBeanFactory().registerSingleton(
AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, beanNameGenerator);
}
/**
* 设置作用域元数据解析器
*/
public void setScopeMetadataResolver(ScopeMetadataResolver scopeMetadataResolver) {
this.reader.setScopeMetadataResolver(scopeMetadataResolver);
this.scanner.setScopeMetadataResolver(scopeMetadataResolver);
}
}
/**
* GenericApplicationContext
* 通用的应用上下文实现
*/
public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {
// Bean工厂
private final DefaultListableBeanFactory beanFactory;
// 资源加载器
@Nullable
private ResourceLoader resourceLoader;
// 是否需要刷新Bean工厂
private boolean freshBeanFactory = true;
/**
* 默认构造方法
*/
public GenericApplicationContext() {
this.beanFactory = new DefaultListableBeanFactory();
}
/**
* 带Bean工厂的构造方法
*/
public GenericApplicationContext(DefaultListableBeanFactory beanFactory) {
Assert.notNull(beanFactory, "BeanFactory must not be null");
this.beanFactory = beanFactory;
this.beanFactory.setCacheBeanMetadata(false);
}
/**
* 带父上下文的构造方法
*/
public GenericApplicationContext(@Nullable ApplicationContext parent) {
this();
setParent(parent);
}
/**
* 设置资源加载器
*/
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
/**
* 获取资源加载器
*/
@Override
public ResourceLoader getResourceLoader() {
return (this.resourceLoader != null ? this.resourceLoader : this);
}
/**
* 获取类加载器
*/
@Override
@Nullable
public ClassLoader getClassLoader() {
if (this.resourceLoader != null) {
return this.resourceLoader.getClassLoader();
}
return super.getClassLoader();
}
/**
* 刷新Bean工厂
*/
@Override
protected final void refreshBeanFactory() throws IllegalStateException {
if (!this.refreshed.compareAndSet(false, true)) {
throw new IllegalStateException(
"GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
}
this.beanFactory.setSerializationId(getId());
}
/**
* 获取Bean工厂
*/
@Override
public final ConfigurableListableBeanFactory getBeanFactory() {
return this.beanFactory;
}
/**
* 注册Bean定义
*/
@Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException {
this.beanFactory.registerBeanDefinition(beanName, beanDefinition);
}
/**
* 移除Bean定义
*/
@Override
public void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException {
this.beanFactory.removeBeanDefinition(beanName);
}
/**
* 获取Bean定义
*/
@Override
public BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException {
return this.beanFactory.getBeanDefinition(beanName);
}
/**
* 判断是否包含Bean定义
*/
@Override
public boolean containsBeanDefinition(String beanName) {
return this.beanFactory.containsBeanDefinition(beanName);
}
/**
* 获取Bean定义名称数组
*/
@Override
public String[] getBeanDefinitionNames() {
return this.beanFactory.getBeanDefinitionNames();
}
/**
* 获取Bean定义数量
*/
@Override
public int getBeanDefinitionCount() {
return this.beanFactory.getBeanDefinitionCount();
}
/**
* 判断是否为Bean名称
*/
@Override
public boolean isBeanNameInUse(String beanName) {
return this.beanFactory.isBeanNameInUse(beanName);
}
}
5. ApplicationContext实际使用示例
/*
* ApplicationContext实际使用示例
*/
/**
* 配置类示例
*/
@Configuration
@ComponentScan(basePackages = "com.example")
@PropertySource("classpath:application.properties")
@EnableAspectJAutoProxy
public class AppConfig {
/**
* 数据源Bean
*/
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
/**
* JdbcTemplate Bean
*/
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
/**
* 消息源Bean
*/
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
/**
* 应用事件广播器Bean
*/
@Bean
public ApplicationEventMulticaster applicationEventMulticaster() {
SimpleApplicationEventMulticaster eventMulticaster = new SimpleApplicationEventMulticaster();
eventMulticaster.setTaskExecutor(Executors.newSingleThreadExecutor());
return eventMulticaster;
}
}
/**
* 服务类示例
*/
@Service
public class UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private ApplicationEventPublisher eventPublisher;
@Autowired
private MessageSource messageSource;
/**
* 创建用户
*/
public User createUser(String name, String email) {
// 创建用户逻辑
User user = new User(name, email);
// 发布用户创建事件
eventPublisher.publishEvent(new UserCreatedEvent(this, user));
return user;
}
/**
* 获取用户消息
*/
public String getUserMessage(String code, Locale locale) {
return messageSource.getMessage(code, null, locale);
}
}
/**
* 事件监听器示例
*/
@Component
public class UserEventListener {
private static final Logger logger = LoggerFactory.getLogger(UserEventListener.class);
/**
* 监听用户创建事件
*/
@EventListener
public void handleUserCreated(UserCreatedEvent event) {
User user = event.getUser();
logger.info("用户已创建: {} ({})", user.getName(), user.getEmail());
// 发送欢迎邮件等操作
sendWelcomeEmail(user);
}
/**
* 监听上下文刷新事件
*/
@EventListener
public void handleContextRefresh(ContextRefreshedEvent event) {
logger.info("应用上下文已刷新: {}", event.getApplicationContext().getDisplayName());
}
/**
* 监听上下文关闭事件
*/
@EventListener
public void handleContextClosed(ContextClosedEvent event) {
logger.info("应用上下文已关闭: {}", event.getApplicationContext().getDisplayName());
}
/**
* 发送欢迎邮件
*/
private void sendWelcomeEmail(User user) {
// 邮件发送逻辑
logger.info("发送欢迎邮件给用户: {}", user.getEmail());
}
}
/**
* 用户实体类
*/
public class User {
private String name;
private String email;
public User(String name, String email) {
this.name = name;
this.email = email;
}
// Getters and Setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}
/**
* 用户创建事件
*/
public class UserCreatedEvent extends ApplicationEvent {
private final User user;
public UserCreatedEvent(Object source, User user) {
super(source);
this.user = user;
}
public User getUser() {
return user;
}
}
/**
* 应用程序主类
*/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
// 方式1: 使用AnnotationConfigApplicationContext
testAnnotationConfigApplicationContext();
// 方式2: 使用ClassPathXmlApplicationContext
testClassPathXmlApplicationContext();
// 方式3: 使用SpringBootApplication
runSpringBootApplication(args);
}
/**
* 测试AnnotationConfigApplicationContext
*/
private static void testAnnotationConfigApplicationContext() {
System.out.println("=== 测试AnnotationConfigApplicationContext ===");
try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
// 注册配置类
context.register(AppConfig.class);
// 刷新上下文
context.refresh();
// 获取Bean
UserService userService = context.getBean(UserService.class);
// 使用Bean
User user = userService.createUser("张三", "zhangsan@example.com");
System.out.println("创建用户: " + user.getName());
// 获取消息
String message = userService.getUserMessage("user.welcome", Locale.CHINA);
System.out.println("用户消息: " + message);
// 等待事件处理完成
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 测试ClassPathXmlApplicationContext
*/
private static void testClassPathXmlApplicationContext() {
System.out.println("=== 测试ClassPathXmlApplicationContext ===");
try (ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml")) {
// 获取Bean
UserService userService = context.getBean(UserService.class);
// 使用Bean
User user = userService.createUser("李四", "lisi@example.com");
System.out.println("创建用户: " + user.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 运行Spring Boot应用
*/
private static void runSpringBootApplication(String[] args) {
System.out.println("=== 运行Spring Boot应用 ===");
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
try {
// 获取Bean
UserService userService = context.getBean(UserService.class);
// 使用Bean
User user = userService.createUser("王五", "wangwu@example.com");
System.out.println("创建用户: " + user.getName());
// 等待一段时间观察事件处理
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭上下文
context.close();
}
}
}
/**
* XML配置文件示例 (applicationContext.xml)
*/
/*
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 组件扫描 -->
<context:component-scan base-package="com.example"/>
<!-- 属性配置 -->
<context:property-placeholder location="classpath:application.properties"/>
<!-- 数据源配置 -->
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource">
<property name="jdbcUrl" value="${spring.datasource.url}"/>
<property name="username" value="${spring.datasource.username}"/>
<property name="password" value="${spring.datasource.password}"/>
</bean>
<!-- JdbcTemplate配置 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource"/>
</bean>
<!-- 消息源配置 -->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean>
</beans>
*/
6. 最佳实践和注意事项
/*
* ApplicationContext最佳实践
*/
/**
* 正确的ApplicationContext使用方式
*/
public class GoodApplicationContextUsage {
private static final Logger logger = LoggerFactory.getLogger(GoodApplicationContextUsage.class);
/**
* 正确的上下文创建和使用
*/
public void correctUsage() {
// 方式1: 使用try-with-resources确保资源释放
try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
context.register(AppConfig.class);
context.refresh();
// 使用上下文
performBusinessLogic(context);
}
// 方式2: 手动管理生命周期
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
try {
context.register(AppConfig.class);
context.refresh();
// 使用上下文
performBusinessLogic(context);
} finally {
// 确保上下文被正确关闭
if (context.isActive()) {
context.close();
}
}
}
/**
* 执行业务逻辑
*/
private void performBusinessLogic(ApplicationContext context) {
// 通过类型获取Bean
UserService userService = context.getBean(UserService.class);
// 通过名称和类型获取Bean
JdbcTemplate jdbcTemplate = context.getBean("jdbcTemplate", JdbcTemplate.class);
// 检查Bean是否存在
if (context.containsBean("messageSource")) {
MessageSource messageSource = context.getBean("messageSource", MessageSource.class);
// 使用消息源
}
// 获取所有特定类型的Bean
Map<String, UserService> userServices = context.getBeansOfType(UserService.class);
// 发布自定义事件
context.publishEvent(new CustomEvent(this, "业务事件"));
}
/**
* 自定义事件
*/
public static class CustomEvent extends ApplicationEvent {
private final String message;
public CustomEvent(Object source, String message) {
super(source);
this.message = message;
}
public String getMessage() {
return message;
}
}
}
/**
* 避免的错误使用方式
*/
public class BadApplicationContextUsage {
/**
* 错误的上下文使用
*/
public void badUsage() {
// 错误1: 不关闭上下文导致资源泄露
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(AppConfig.class);
context.refresh();
// 忘记调用context.close()
// 错误2: 在错误的时间获取Bean
try {
UserService userService = context.getBean(UserService.class); // 可能抛出异常
} catch (IllegalStateException e) {
// 上下文未刷新或已关闭
}
// 错误3: 不处理异常
// 可能导致程序异常终止
// 正确的做法应该是:
if (context.isActive()) {
UserService userService = context.getBean(UserService.class);
// 使用Bean
}
}
}
/**
* 高性能的ApplicationContext使用
*/
@Component
public class HighPerformanceApplicationContextUsage {
// 注入ApplicationContext而不是每次都创建
@Autowired
private ApplicationContext applicationContext;
/**
* 高效的Bean获取
*/
public void efficientBeanAccess() {
// 使用注入的ApplicationContext
UserService userService = applicationContext.getBean(UserService.class);
// 缓存经常使用的Bean引用
UserService cachedUserService = getCachedUserService();
// 批量获取Bean
Map<String, UserService> userServices = applicationContext.getBeansOfType(UserService.class);
}
// 缓存Bean引用
private UserService cachedUserService;
private UserService getCachedUserService() {
if (cachedUserService == null) {
cachedUserService = applicationContext.getBean(UserService.class);
}
return cachedUserService;
}
}
/**
* 线程安全的ApplicationContext使用
*/
@Component
public class ThreadSafeApplicationContextUsage {
@Autowired
private ApplicationContext applicationContext;
// 使用线程安全的集合缓存Bean
private final Map<String, Object> beanCache = new ConcurrentHashMap<>();
/**
* 线程安全的Bean获取
*/
public <T> T getBeanSafely(Class<T> beanType) {
String cacheKey = beanType.getName();
// 先从缓存获取
Object cachedBean = beanCache.get(cacheKey);
if (cachedBean != null) {
return beanType.cast(cachedBean);
}
// 同步创建和缓存
synchronized (beanCache) {
cachedBean = beanCache.get(cacheKey);
if (cachedBean != null) {
return beanType.cast(cachedBean);
}
T bean = applicationContext.getBean(beanType);
beanCache.put(cacheKey, bean);
return bean;
}
}
/**
* 清除缓存
*/
public void clearCache() {
beanCache.clear();
}
}
/**
* 条件化的ApplicationContext配置
*/
@Configuration
@ConditionalOnProperty(name = "app.enabled", havingValue = "true", matchIfMissing = true)
public class ConditionalAppConfig {
/**
* 条件化的Bean创建
*/
@Bean
@ConditionalOnMissingBean
public UserService userService() {
return new DefaultUserService();
}
/**
* 环境特定的Bean创建
*/
@Bean
@Profile("production")
public DataSource productionDataSource() {
// 生产环境数据源配置
return createProductionDataSource();
}
@Bean
@Profile("development")
public DataSource developmentDataSource() {
// 开发环境数据源配置
return createDevelopmentDataSource();
}
private DataSource createProductionDataSource() {
// 生产数据源创建逻辑
return new HikariDataSource();
}
private DataSource createDevelopmentDataSource() {
// 开发数据源创建逻辑
return new HikariDataSource();
}
}
7. 核心设计要点总结
7.1 设计目的
- 提供统一的配置管理入口
- 实现Bean的生命周期管理
- 支持企业级特性(国际化、事件发布等)
- 提供层次化配置管理
- 支持多种配置方式
7.2 核心功能
- Bean管理: 配置、创建、生命周期管理
- 资源加载: 统一的资源访问机制
- 事件发布: 应用事件机制
- 国际化: 消息源和本地化支持
- 环境管理: 配置属性和环境抽象
- AOP支持: 面向切面编程集成
7.3 生命周期管理
- 创建: 构造ApplicationContext实例
- 刷新: refresh()方法初始化上下文
- 运行: 应用程序正常运行
- 关闭: close()方法释放资源
7.4 常见实现类
- ClassPathXmlApplicationContext: 基于类路径XML配置
- FileSystemXmlApplicationContext: 基于文件系统XML配置
- AnnotationConfigApplicationContext: 基于注解配置
- GenericApplicationContext: 通用实现
- WebApplicationContext: Web应用上下文
7.5 使用建议
- 正确管理生命周期: 确保上下文被正确关闭
- 合理使用注入: 优先使用依赖注入而非手动获取Bean
- 异常处理: 适当处理可能发生的异常
- 性能考虑: 避免频繁创建和销毁上下文
- 线程安全: 确保多线程环境下的正确使用
7.6 最佳实践
- 使用try-with-resources确保资源释放
- 合理使用配置注解和XML配置
- 实现适当的事件监听和处理
- 使用Profile进行环境配置管理
- 实现条件化的Bean创建
- 注意上下文的层次化管理
ApplicationContext作为Spring框架的核心组件,为开发者提供了强大而灵活的配置管理能力,是构建企业级Java应用的基础。

742

被折叠的 条评论
为什么被折叠?



