ApplicationContext和ConfigurableApplicationContext解析

Spring框架:ApplicationContext与ConfigurableApplicationContext详解
本文探讨Spring框架中的ApplicationContext和ConfigurableApplicationContext接口,分析它们在IOC容器中的角色和区别。ApplicationContext提供了高级IOC规范,包括事件发布、资源解析等功能,而ConfigurableApplicationContext侧重配置,具备更多的设置选项。文章详细解析了ConfigurableApplicationContext的各种配置方法,如环境变量、容器启动等,并提出了关于Bean名称转换、启动程序设置和监听器作用的问题。

这里是我学习Spirng IOC开始文章,改文章中整合了Spring IOC体系的相关类和接口的源码解析。
Spring IOC学习开始

正文开始

既然介绍这两个接口,自然要知道这两个接口在IOC整个体系中的位置和两者之间的联系。

ApplicationContext定了高级容器的基本规范,其实他也不是直接继承BeanFactory基础容器,可以看到ApplicationContext直接父接口对BeanFactory进行很多拓展其中就包括:

  • 事件的注册和发布
  • 消息解析
  • 资源解析
  • Bean工厂层级管理
  • 监听器
  • 容器环境
    通过以上拓展,我们基本可以知道高级IOC容器有哪些特点,这也是学习整个ApplicationContext容器重点了解的部分。

再比较ApplicationContext和ConfigurableApplicationContext定义的方法以及下图层级关系,ConfigurableApplicationContext是ApplicationContext的子接口,也就包含了ApplicationContext。通过方法可以知道,ConfigurableApplicationContext重在对各种属性的配置,而ApplicationContext接口主要各种属性的get方法。

Spring这种将get和set分开到两个接口的设计增大了属性设置和获取的灵活性,将两者分开也更加清晰。在以后的解决方案设计中,可以参考,将配置信息和获取信息分开,两者互不干扰,在保证重要的基础属性不变的情况,可以按需进行拓展。其实Spring的框架设计中应用了大量的装饰者模式,这也是高拓展点的需要
在这里插入图片描述

1. ApplicationContext

该类提供了高级IOC规范
其中有几个注意点:

  • 从ListableBeanFactory接口继承来的:用于访问应用组件的工厂方法
  • 从ResourceLoader接口继承来的:用通用的方式加载文件资源
  • 从ApplicationEventPublisher接口继承来的:注册和发布事件
  • 从MessageSource接口继承来的:处理消息,支持国际化

从父应用上下文定义的在子上下文中将始终保持优先。

public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,
		MessageSource, ApplicationEventPublisher, ResourcePatternResolver {

	/**
	 * 返回一个唯一的应用上下文id
	 * @return the unique id of the context, or {@code null} if none
	 */
	@Nullable
	String getId();

	/**
	 * 返回已经部署的该应用上下文的名称.
	 * @return a name for the deployed application, or the empty String by default
	 */
	String getApplicationName();

	/**
	 * 返回此上下文友好的名称---这有什么用呢?
	 * @return a display name for this context (never {@code null})
	 */
	String getDisplayName();

	/**
	 * 返回该上下文第一次被加载的时间戳
	 * @return the timestamp (ms) when this context was first loaded
	 */
	long getStartupDate();

	/**
	 *返回父应用上下文, 如果没有父上下文,该上下文就是在上下文层次的根
	 * @return the parent context, or {@code null} if there is no parent
	 */
	@Nullable
	ApplicationContext getParent();


	AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException;

}

这其中对AutowireCapableBeanFactory getAutowireCapableBeanFactory()方法有疑惑,然后网上百度了一下。Spring提供了一种机制,能够为第三方框架赋能,让Spring去管理的Bean去装配和填充那些没有被SpringIOC管理的bean。也就是Spring提供了使用第三方框架的能力,能够做到无缝的将第三方框架整合到Spring中来进行使用,Junit与Quartz借用了这种机制为自己赋能。

2. ConfigurableApplicationContext

整体结构图
在这里插入图片描述
这个图可以看出,ConfigurableApplicationContext是ApplicationContext的子类,该接口的主要任务就是配置应用程序上下文功能。

/**
 * SPI interface to be implemented by most if not all application contexts.
 * Provides facilities to configure an application context in addition
 * to the application context client methods in the
 * {@link org.springframework.context.ApplicationContext} interface.
 *
 * <p>Configuration and lifecycle methods are encapsulated here to avoid
 * making them obvious to ApplicationContext client code. The present
 * methods should only be used by startup and shutdown code.
 * ~~~~~~~~~~~~~~~~~~~~~~~~
 * 中文解释:
 * SPI接口将由大多数(而不是全部)应用程序上下文实现。 
 * 除了ApplicationContext接口中的ApplicationContext程序上下文客户端方法外,
 * 还提供了配置应用程序上下文的功能。
 * 配置和生命周期方法在此处进行了封装,以避免对ApplicationContext客户端代码显而易见。 
 * 本方法仅应由启动和关闭代码使用
 * ~~~~~~~~~~~~~~~~~~~~~~~~
 *
 * @author Juergen Hoeller
 * @author Chris Beams
 * @author Sam Brannen
 * @since 03.11.2003
 */

具体分析

1. 硬性基础属性配置

除了第一个之外,其他的都是将在bean工厂中bean名称为双引号小写的bean的名称改成左边的大写。至于为什么要这样设置,我还没理解?

/**
	 * Any number of these characters are considered delimiters between
	 * multiple context config paths in a single String value.
	 * 在单个String值中,可以将任意数量的这些字符视为多个上下文配置路径之间的分隔符。
	 * 就是设置多个应用上下文配置文件的的分隔符
	 * @see org.springframework.context.support.AbstractXmlApplicationContext#setConfigLocation
	 * @see org.springframework.web.context.ContextLoader#CONFIG_LOCATION_PARAM
	 * @see org.springframework.web.servlet.FrameworkServlet#setContextConfigLocation
	 */
	String CONFIG_LOCATION_DELIMITERS = ",; \t\n";

	/**
	 * Name of the ConversionService bean in the factory.
	 * If none is supplied, default conversion rules apply.
	 * @since 3.0
	 * @see org.springframework.core.convert.ConversionService
	 */
	String CONVERSION_SERVICE_BEAN_NAME = "conversionService";

	/**
	 * Name of the LoadTimeWeaver bean in the factory. If such a bean is supplied,
	 * the context will use a temporary ClassLoader for type matching, in order
	 * to allow the LoadTimeWeaver to process all actual bean classes.
	 * @since 2.5
	 * @see org.springframework.instrument.classloading.LoadTimeWeaver
	 */
	String LOAD_TIME_WEAVER_BEAN_NAME = "loadTimeWeaver";

	/**
	 * Name of the {@link Environment} bean in the factory.
	 * @since 3.1
	 */
	String ENVIRONMENT_BEAN_NAME = "environment";

	/**
	 * Name of the System properties bean in the factory.
	 * @see java.lang.System#getProperties()
	 */
	String SYSTEM_PROPERTIES_BEAN_NAME = "systemProperties";

	/**
	 * Name of the System environment bean in the factory.
	 * @see java.lang.System#getenv()
	 */
	String SYSTEM_ENVIRONMENT_BEAN_NAME = "systemEnvironment";

	/**
	 * Name of the {@link ApplicationStartup} bean in the factory.
	 * @since 5.3
	 */
	String APPLICATION_STARTUP_BEAN_NAME = "applicationStartup";

	/**
	 * {@link Thread#getName() Name} of the {@linkplain #registerShutdownHook()
	 * shutdown hook} thread: {@value}.
	 * @since 5.2
	 * @see #registerShutdownHook()
	 */
	String SHUTDOWN_HOOK_THREAD_NAME = "SpringContextShutdownHook";

2. 设置容器id

/**
	 * Set the unique id of this application context.
	 * 给应用上下文-容器设置唯一的id
	 * @since 3.0
	 */
void setId(String id);

3. 设置父容器

/**
	 * Set the parent of this application context.
	 * <p>Note that the parent shouldn't be changed: It should only be set outside
	 * a constructor if it isn't available when an object of this class is created,
	 * for example in case of WebApplicationContext setup.
	 * 为该应用上下文设置父级
	 * 请注意,不应更改父级:仅当在创建此类的对象时不可用
	 * (例如在WebApplicationContext安装的情况下)时,才应在构造函数外部设置父级。
	 * @param parent the parent context
	 * @see org.springframework.web.context.ConfigurableWebApplicationContext
	 */
	 void setParent(@Nullable ApplicationContext parent);

3. 设置环境变量

/**
	 * Set the {@code Environment} for this application context.
	 * 为该应用上下文设置环境变量
	 * @param environment the new environment
	 * @since 3.1
	 */
	void setEnvironment(ConfigurableEnvironment environment);

4. 获取环境变量配置信息

/**
	 * Return the {@code Environment} for this application context in configurable
	 * form, allowing for further customization.
	 * 以可配置的形式返回此应用程序上下文的{@code Environment},以便进行进一步的自定义
	 * @since 3.1
	 */
	@Override
	ConfigurableEnvironment getEnvironment();

5. 设置应用启动

/**
	 * Set the {@link ApplicationStartup} for this application context.
	 * <p>This allows the application context to record metrics
	 * during startup.
	 * 这允许在启动期间应用程序上下文记录指标
	 * @param applicationStartup the new context event factory
	 * @since 5.3
	 */
	void setApplicationStartup(ApplicationStartup applicationStartup);

6. 添加后置处理器

不知道这个后置处理器的作用,在哪个后面进行使用呢?

/**
	 * Add a new BeanFactoryPostProcessor that will get applied to the internal
	 * bean factory of this application context on refresh, before any of the
	 * bean definitions get evaluated. To be invoked during context configuration.
	 * @param postProcessor the factory processor to register
	 */
	void addBeanFactoryPostProcessor(BeanFactoryPostProcessor postProcessor);

7. 应用监听器

在IOC的很多地方都能见到坚挺器的身影,那监听器到底起到什么作用呢?

/**
	 * Add a new ApplicationListener that will be notified on context events
	 * such as context refresh and context shutdown.
	 * <p>Note that any ApplicationListener registered here will be applied
	 * on refresh if the context is not active yet, or on the fly with the
	 * current event multicaster in case of a context that is already active.
	 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	 * 中文解释:
	 * 添加一个在应用监听器,他将在应用事件被发现,列如应用事件:刷新和关闭应用上下文
	 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	 * @param listener the ApplicationListener to register
	 * @see org.springframework.context.event.ContextRefreshedEvent
	 * @see org.springframework.context.event.ContextClosedEvent
	 */
	void addApplicationListener(ApplicationListener<?> listener);

8. 设置ClassLoader

/**
	 * Specify the ClassLoader to load class path resources and bean classes with.
	 * <p>This context class loader will be passed to the internal bean factory.
	 * ~~~~~~~~~~~~~~~~~
	 * 指定ClassLoader以加载类路径资源和Bean类。
	 * 该上下文类加载器将传递给内部bean工厂
	 * ~~~~~~~~~~~~~~~~~
	 * @since 5.2.7
	 * @see org.springframework.core.io.DefaultResourceLoader#DefaultResourceLoader(ClassLoader)
	 * @see org.springframework.beans.factory.config.ConfigurableBeanFactory#setBeanClassLoader
	 */
	void setClassLoader(ClassLoader classLoader);

ClassLoader 在之前查看资源解析器中遇到过,在容器创建中少不了对配置文件的解析和类加载,这里提供了类加载设置接口。该文件加载器还要被加载到内部bean工厂中使用。

9. 增加协议解析器

/**
	 * Register the given protocol resolver with this application context,
	 * allowing for additional resource protocols to be handled.
	 * <p>Any such resolver will be invoked ahead of this context's standard
	 * resolution rules. It may therefore also override any default rules.
	 * ~~~~~~~~~~~~~~~~~~~
	 * 想该应用上下文注册给定的协议解析器
	 * 允许处理其他协议资源
	 * 任何此类解析程序都将在此上下文的标准解析规则之前调用。
	 * 因此,它也可以覆盖任何默认规则。
	 * ~~~~~~~~~~~~~~~~~~~
	 * @since 4.3
	 */
	void addProtocolResolver(ProtocolResolver resolver);

协议解析器我在资源解析中也看到可,除了默认的资源解析器之外,Spring还提供接口,允许用户注册增加其他资源解析器,大大增强了Spring框架的拓展性。
其实也就是,Spring将整体的流程定义好了,在整个流程的每个环节都为用户提供了自定义点,增加灵活性,只要各个环节的数据结构规定好,在各个环节中,用户可以自由发挥。这种设计理念值得借鉴。

10. 刷新容器

/**
	 * Load or refresh the persistent representation of the configuration, which
	 * might be from Java-based configuration, an XML file, a properties file, a
	 * relational database schema, or some other format.
	 * 加载或刷新配置的持久表示形式,
	 * 该表示形式可能来自基于Java的配置,XML文件,属性文件,关系数据库模式或其他某种格式。
	 * <p>As this is a startup method, it should destroy already created singletons
	 * if it fails, to avoid dangling resources. In other words, after invocation
	 * of this method, either all or no singletons at all should be instantiated.
	 * 因为这是一个启动方法(在后面的创建容器方法,该方法当做容器创建方法),如果失败了,它应该销毁样创
	 * 的单例,换句话说,在调用此方法之后,应实例化所有单例或根本不实例化。
	 * @throws BeansException if the bean factory could not be initialized
	 * @throws IllegalStateException if already initialized and multiple refresh
	 * attempts are not supported
	 */
	void refresh() throws BeansException, IllegalStateException;

11. 注册关闭挂钩

/**
	 * Register a shutdown hook with the JVM runtime, closing this context
	 * on JVM shutdown unless it has already been closed at that time.
	 * <p>This method can be called multiple times. Only one shutdown hook
	 * (at max) will be registered for each context instance.
	 * <p>As of Spring Framework 5.2, the {@linkplain Thread#getName() name} of
	 * the shutdown hook thread should be {@link #SHUTDOWN_HOOK_THREAD_NAME}.
	 * @see java.lang.Runtime#addShutdownHook
	 * @see #close()
	 */
	void registerShutdownHook();

12. 关闭应用上下文

/**
	 * Close this application context, releasing all resources and locks that the
	 * implementation might hold. This includes destroying all cached singleton beans.
	 * <p>Note: Does <i>not</i> invoke {@code close} on a parent context;
	 * parent contexts have their own, independent lifecycle.
	 * 关闭此应用程序上下文,释放实现可能持有的所有资源和锁。 
	 * 这包括销毁所有缓存的单例bean。
	 * 注意:不会在父上下文上调用close ; 父级上下文具有自己的独立生命周期。
	 * <p>This method can be called multiple times without side effects: Subsequent
	 * {@code close} calls on an already closed context will be ignored.
	 * 这个方法可以多次调用此方法而没有副作用:在已经关闭的上下文上进行的后续close调用将被忽略。
	 */
	@Override
	void close();

13. 判断应用上下是否关闭,是否处于活跃状态

/**
	 * Determine whether this application context is active, that is,
	 * whether it has been refreshed at least once and has not been closed yet.
	 * 确定尬应用上下文是否处于活动状态,,即,是否至少刷新一次并且尚未关闭。
	 * @return whether the context is still active
	 * @see #refresh()
	 * @see #close()
	 * @see #getBeanFactory()
	 */
	boolean isActive();

14. 获取内部bean工厂

/**
	 * Return the internal bean factory of this application context.
	 * Can be used to access specific functionality of the underlying factory.
	 * <p>Note: Do not use this to post-process the bean factory; singletons
	 * will already have been instantiated before. Use a BeanFactoryPostProcessor
	 * to intercept the BeanFactory setup process before beans get touched.
	 * <p>Generally, this internal factory will only be accessible while the context
	 * is active, that is, in-between {@link #refresh()} and {@link #close()}.
	 * The {@link #isActive()} flag can be used to check whether the context
	 * is in an appropriate state.
	 * ~~~~~~~~~~~~~~~~
	 * 返回该应用上下文的内部bean工厂
	 * ~~~~~~~~~~~~~~~~
	 * @return the underlying bean factory
	 * @throws IllegalStateException if the context does not hold an internal
	 * bean factory (usually if {@link #refresh()} hasn't been called yet or
	 * if {@link #close()} has already been called)
	 * @see #isActive()
	 * @see #refresh()
	 * @see #close()
	 * @see #addBeanFactoryPostProcessor
	 */
	ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;

问题

1. 关于一开始对某些名称的bean名进行大写替换,为什么要这么做呢?

2. 为什么要给应用程序上下文设置启动程序?

3. 容器创建中,监听器的作用是什么呢?

参考文章

介绍依赖注入的发展流程

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值