Spring ConfigurableApplicationContext源码详解(详细注释版)
1. ConfigurableApplicationContext接口源码
/*
* ConfigurableApplicationContext接口是Spring框架中ApplicationContext的可配置扩展
* 提供了对应用程序上下文的完整配置和生命周期管理能力
* 是Spring应用上下文实现类的主要接口
*
* ConfigurableApplicationContext的作用:
* 1. 上下文生命周期管理(刷新、关闭)
* 2. 配置管理(环境、BeanFactory后处理器)
* 3. 事件系统配置
* 4. 启动阶段管理
* 5. 完整的上下文控制能力
*
* 注意事项:
* - 提供了比ApplicationContext更丰富的配置方法
* - 是ApplicationContext实现类的主要接口
* - 支持完整的生命周期管理
*/
package org.springframework.context;
import java.io.Closeable;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.lang.Nullable;
/**
* 可配置的应用程序上下文接口
* 提供了对ApplicationContext的配置和生命周期管理能力
*
* ConfigurableApplicationContext在ApplicationContext基础上增加了:
* 1. 上下文生命周期管理(刷新、关闭)
* 2. 配置管理(环境、BeanFactory后处理器)
* 3. 事件系统配置
* 4. 启动阶段管理
* 5. 完整的上下文控制能力
*
* 主要功能:
* - 上下文生命周期管理
* - 配置管理
* - 事件系统管理
* - BeanFactory访问
* - 环境管理
*
* 执行顺序:
* 1. setId() - 设置ID
* 2. setEnvironment() - 设置环境
* 3. addBeanFactoryPostProcessor() - 添加BeanFactory后处理器
* 4. addApplicationListener() - 添加监听器
* 5. refresh() - 刷新上下文
* 6. close() - 关闭上下文
*/
public interface ConfigurableApplicationContext extends ApplicationContext, Lifecycle, Closeable {
/**
* 用于在关闭时取消注册的关闭钩子的线程名称
*/
String SHUTDOWN_HOOK_THREAD_NAME = "SpringContextShutdownHook";
/**
* 设置此应用程序上下文的ID
*
* @param id 应用程序上下文的ID
*
* 使用场景:
* - 自定义上下文标识
* - 分布式系统中的上下文管理
* - 配置管理
* - 日志标识
*/
void setId(String id);
/**
* 设置此应用程序上下文的父上下文
*
* @param parent 父上下文
*
* 使用场景:
* - 层次化上下文配置
* - 配置继承
* - Bean查找的层次结构
* - 多模块应用的上下文组织
*/
void setParent(@Nullable ApplicationContext parent);
/**
* 设置此应用程序上下文的Environment
*
* @param environment Environment实例
*
* 使用场景:
* - 自定义环境配置
* - 多环境支持
* - 配置属性管理
* - Profile管理
*/
void setEnvironment(ConfigurableEnvironment environment);
/**
* 返回此应用程序上下文的内部BeanFactory
*
* @return 内部BeanFactory
* @throws IllegalStateException 如果上下文未刷新或已关闭
*
* 使用场景:
* - 直接访问BeanFactory
* - 高级配置操作
* - 自定义Bean管理
* - 手动注册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关闭时优雅地关闭此上下文
*
* 使用场景:
* - 自动资源清理
* - 优雅关闭应用
* - 防止资源泄露
* - 生产环境的标准做法
*
* 注意事项:
* - 通常在refresh()后调用
* - 可以多次调用但只注册一次
* - 可以通过setRegisterShutdownHook(false)取消
*/
void registerShutdownHook();
/**
* 关闭此应用程序上下文,释放所有资源和锁
*
* 此方法确保:
* 1. 发布ContextClosedEvent事件
* 2. 销毁所有单例Bean
* 3. 关闭生命周期Bean
* 4. 清理资源
* 5. 设置关闭状态
*
* 使用场景:
* - 应用关闭
* - 资源清理
* - 测试环境清理
* - 手动控制上下文生命周期
*/
@Override
void close();
/**
* 判断此应用程序上下文是否处于激活状态
*
* 激活状态的含义:
* - 上下文已成功刷新
* - 尚未关闭
* - 可以正常获取Bean
*
* @return 如果上下文处于激活状态返回true
*
* 使用场景:
* - 状态检查
* - 条件化操作
* - 健康检查
* - 防止重复操作
*/
boolean isActive();
/**
* 加载或刷新配置的持久化表示
*
* 刷新过程包括:
* 1. 准备刷新上下文
* 2. 获取或创建BeanFactory
* 3. 准备BeanFactory
* 4. 后处理BeanFactory
* 5. 调用BeanFactoryPostProcessor
* 6. 注册BeanPostProcessor
* 7. 初始化消息源
* 8. 初始化事件广播器
* 9. 子类特殊刷新
* 10. 注册监听器
* 11. 实例化单例Bean
* 12. 完成刷新
*
* @throws BeansException 如果无法初始化Bean工厂
* @throws IllegalStateException 如果已经初始化或已关闭
*
* 使用场景:
* - 初始化应用上下文
* - 重新加载配置
* - 动态配置更新
* - 测试环境初始化
*/
void refresh() throws BeansException, IllegalStateException;
}
2. AbstractApplicationContext核心实现
/*
* AbstractApplicationContext是ConfigurableApplicationContext的主要抽象实现
* 提供了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 LifecycleProcessor lifecycleProcessor;
// 消息源
@Nullable
private MessageSource messageSource;
// 内部BeanFactory
@Nullable
protected ConfigurableListableBeanFactory beanFactory;
// 关闭钩子
@Nullable
private Thread shutdownHook;
// 虚拟机关闭钩子是否已注册
private volatile boolean shutdownHookRegistered = false;
/**
* 构造方法
*/
public AbstractApplicationContext() {
// 使用默认资源模式解析器
}
/**
* 带父上下文的构造方法
*/
public AbstractApplicationContext(@Nullable ApplicationContext parent) {
this();
setParent(parent);
}
/**
* 设置父上下文
*/
@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<>();
}
/**
* 初始化属性源
* 子类可以重写此方法以添加自定义属性源
*/
protected void initPropertySources() {
// 默认实现为空,子类可以重写
}
/**
* 获取新的Bean工厂
*/
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
}
/**
* 准备Bean工厂
* 配置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");
}
}
}
/**
* 获取环境
*/
@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;
}
/**
* 获取消息源
*/
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正在关闭
}
}
}
}
}
}
3. 具体ConfigurableApplicationContext实现
/*
* 具体的ConfigurableApplicationContext实现类
*/
/**
* 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);
}
}
/**
* 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);
}
}
/**
* 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;
}
}
4. ConfigurableApplicationContext实际使用示例
/*
* ConfigurableApplicationContext实际使用示例
*/
/**
* 配置类示例
*/
@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);
// 添加BeanFactoryPostProcessor
context.addBeanFactoryPostProcessor(new CustomBeanFactoryPostProcessor());
// 添加ApplicationListener
context.addApplicationListener(new CustomApplicationListener());
// 设置环境
ConfigurableEnvironment environment = new StandardEnvironment();
environment.setActiveProfiles("development");
context.setEnvironment(environment);
// 刷新上下文
context.refresh();
// 注册关闭钩子
context.registerShutdownHook();
// 获取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);
// 检查上下文状态
System.out.println("上下文激活状态: " + context.isActive());
System.out.println("上下文启动日期: " + new Date(context.getStartupDate()));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 测试ClassPathXmlApplicationContext
*/
private static void testClassPathXmlApplicationContext() {
System.out.println("=== 测试ClassPathXmlApplicationContext ===");
try (ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml")) {
// 设置ID
context.setId("test-context");
// 添加监听器
context.addApplicationListener(event -> {
if (event instanceof ContextRefreshedEvent) {
System.out.println("XML上下文已刷新");
}
});
// 获取Bean
UserService userService = context.getBean(UserService.class);
// 使用Bean
User user = userService.createUser("李四", "lisi@example.com");
System.out.println("创建用户: " + user.getName());
// 检查状态
System.out.println("上下文ID: " + context.getId());
System.out.println("显示名称: " + context.getDisplayName());
} 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);
// 检查上下文信息
System.out.println("应用名称: " + context.getApplicationName());
System.out.println("显示名称: " + context.getDisplayName());
System.out.println("启动日期: " + new Date(context.getStartupDate()));
System.out.println("激活状态: " + context.isActive());
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭上下文
context.close();
System.out.println("上下文已关闭: " + context.isClosed());
}
}
}
/**
* 自定义BeanFactoryPostProcessor
*/
@Component
public class CustomBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
private static final Logger logger = LoggerFactory.getLogger(CustomBeanFactoryPostProcessor.class);
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
logger.info("自定义BeanFactoryPostProcessor执行");
// 修改Bean定义
String[] beanNames = beanFactory.getBeanDefinitionNames();
for (String beanName : beanNames) {
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
logger.debug("处理Bean定义: {} - {}", beanName, beanDefinition.getBeanClassName());
}
}
}
/**
* 自定义ApplicationListener
*/
@Component
public class CustomApplicationListener implements ApplicationListener<ApplicationContextEvent> {
private static final Logger logger = LoggerFactory.getLogger(CustomApplicationListener.class);
@Override
public void onApplicationEvent(ApplicationContextEvent event) {
if (event instanceof ContextRefreshedEvent) {
logger.info("自定义监听器: 上下文已刷新");
} else if (event instanceof ContextClosedEvent) {
logger.info("自定义监听器: 上下文已关闭");
} else if (event instanceof ContextStartedEvent) {
logger.info("自定义监听器: 上下文已启动");
} else if (event instanceof ContextStoppedEvent) {
logger.info("自定义监听器: 上下文已停止");
}
}
}
/**
* 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>
*/
5. 最佳实践和注意事项
/*
* ConfigurableApplicationContext最佳实践
*/
/**
* 正确的ConfigurableApplicationContext使用方式
*/
public class GoodConfigurableApplicationContextUsage {
private static final Logger logger = LoggerFactory.getLogger(GoodConfigurableApplicationContextUsage.class);
/**
* 正确的上下文创建和使用
*/
public void correctUsage() {
// 方式1: 使用try-with-resources确保资源释放
try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
// 配置上下文
configureContext(context);
// 刷新上下文
context.refresh();
// 注册关闭钩子
context.registerShutdownHook();
// 使用上下文
performBusinessLogic(context);
// 检查状态
logger.info("上下文激活状态: {}", context.isActive());
}
// 方式2: 手动管理生命周期
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
try {
configureContext(context);
context.refresh();
context.registerShutdownHook();
// 使用上下文
performBusinessLogic(context);
// 检查状态
logger.info("上下文启动日期: {}", new Date(context.getStartupDate()));
} finally {
// 确保上下文被正确关闭
if (context.isActive()) {
context.close();
}
logger.info("上下文已关闭: {}", context.isClosed());
}
}
/**
* 配置上下文
*/
private void configureContext(ConfigurableApplicationContext context) {
// 设置ID
context.setId("business-context-" + System.currentTimeMillis());
// 设置显示名称
context.setDisplayName("业务应用上下文");
// 设置环境
ConfigurableEnvironment environment = new StandardEnvironment();
environment.setActiveProfiles("production");
context.setEnvironment(environment);
// 添加BeanFactoryPostProcessor
context.addBeanFactoryPostProcessor(beanFactory -> {
logger.info("添加自定义BeanFactoryPostProcessor");
});
// 添加ApplicationListener
context.addApplicationListener(event -> {
if (event instanceof ContextRefreshedEvent) {
logger.info("上下文刷新完成");
}
});
// 注册配置类
if (context instanceof AnnotationConfigApplicationContext) {
((AnnotationConfigApplicationContext) context).register(AppConfig.class);
}
}
/**
* 执行业务逻辑
*/
private void performBusinessLogic(ConfigurableApplicationContext 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 BadConfigurableApplicationContextUsage {
/**
* 错误的上下文使用
*/
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: 不处理异常
// 可能导致程序异常终止
// 错误4: 重复刷新上下文
try {
context.refresh(); // 第一次
context.refresh(); // 第二次 - 会抛出异常
} catch (IllegalStateException e) {
logger.error("重复刷新上下文", e);
}
// 正确的做法应该是:
if (context.isActive()) {
UserService userService = context.getBean(UserService.class);
// 使用Bean
}
}
}
/**
* 高性能的ConfigurableApplicationContext使用
*/
@Component
public class HighPerformanceConfigurableApplicationContextUsage {
// 注入ApplicationContext而不是每次都创建
@Autowired
private ConfigurableApplicationContext 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;
}
/**
* 动态配置管理
*/
public void dynamicConfiguration() {
// 添加BeanFactoryPostProcessor
applicationContext.addBeanFactoryPostProcessor(beanFactory -> {
// 动态修改Bean定义
logger.info("动态添加BeanFactoryPostProcessor");
});
// 添加ApplicationListener
applicationContext.addApplicationListener(event -> {
logger.info("收到事件: {}", event.getClass().getSimpleName());
});
// 修改环境属性
ConfigurableEnvironment environment = applicationContext.getEnvironment();
environment.getSystemProperties().put("dynamic.property", "dynamic-value");
}
}
/**
* 线程安全的ConfigurableApplicationContext使用
*/
@Component
public class ThreadSafeConfigurableApplicationContextUsage {
@Autowired
private ConfigurableApplicationContext 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 threadSafeContextOperation() {
// 检查上下文状态(线程安全)
if (applicationContext.isActive()) {
// 执行操作
performSafeOperation();
}
}
private void performSafeOperation() {
// 线程安全的操作
synchronized (applicationContext) {
// 安全的上下文操作
logger.info("执行线程安全的上下文操作");
}
}
/**
* 清除缓存
*/
public void clearCache() {
beanCache.clear();
}
}
/**
* 条件化的ConfigurableApplicationContext配置
*/
@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();
}
}
/**
* 自定义ConfigurableApplicationContext扩展
*/
public class CustomApplicationContext extends GenericApplicationContext {
private static final Logger logger = LoggerFactory.getLogger(CustomApplicationContext.class);
// 自定义属性
private String customProperty;
/**
* 设置自定义属性
*/
public void setCustomProperty(String customProperty) {
this.customProperty = customProperty;
}
/**
* 获取自定义属性
*/
public String getCustomProperty() {
return customProperty;
}
/**
* 自定义刷新逻辑
*/
@Override
protected void onRefresh() throws BeansException {
super.onRefresh();
// 执行自定义刷新逻辑
logger.info("执行自定义刷新逻辑,自定义属性: {}", customProperty);
// 初始化自定义组件
initializeCustomComponents();
}
/**
* 初始化自定义组件
*/
private void initializeCustomComponents() {
// 自定义组件初始化逻辑
logger.info("初始化自定义组件");
}
/**
* 自定义关闭逻辑
*/
@Override
protected void doClose() {
// 执行自定义关闭逻辑
logger.info("执行自定义关闭逻辑");
// 清理自定义资源
cleanupCustomResources();
// 调用父类关闭逻辑
super.doClose();
}
/**
* 清理自定义资源
*/
private void cleanupCustomResources() {
// 自定义资源清理逻辑
logger.info("清理自定义资源");
}
}
6. 核心设计要点总结
6.1 设计目的
- 提供完整的上下文配置和管理能力
- 支持上下文生命周期管理
- 提供灵活的配置扩展机制
- 支持企业级应用的复杂需求
6.2 核心功能
- 生命周期管理: 刷新、启动、停止、关闭
- 配置管理: 环境、BeanFactory后处理器、监听器
- 事件系统: 事件发布和监听
- 资源管理: 资源加载和访问
- Bean管理: Bean定义注册和管理
6.3 生命周期管理
- 创建: 构造ApplicationContext实例
- 配置: 设置ID、环境、监听器等
- 刷新: refresh()方法初始化上下文
- 运行: 应用程序正常运行
- 关闭: close()方法释放资源
6.4 常见实现类
- GenericApplicationContext: 通用实现
- AnnotationConfigApplicationContext: 基于注解配置
- ClassPathXmlApplicationContext: 基于类路径XML配置
- FileSystemXmlApplicationContext: 基于文件系统XML配置
- WebApplicationContext: Web应用上下文
6.5 使用建议
- 正确管理生命周期: 确保上下文被正确关闭
- 合理使用配置方法: 根据需要配置上下文
- 异常处理: 适当处理可能发生的异常
- 性能考虑: 避免频繁创建和销毁上下文
- 线程安全: 确保多线程环境下的正确使用
6.6 最佳实践
- 使用try-with-resources确保资源释放
- 合理使用配置注解和XML配置
- 实现适当的事件监听和处理
- 使用Profile进行环境配置管理
- 实现条件化的Bean创建
- 注意上下文的层次化管理
- 注册关闭钩子确保优雅关闭
ConfigurableApplicationContext作为Spring框架的核心组件,为开发者提供了强大而灵活的上下文管理能力,是构建企业级Java应用的基础。

8369

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



