Spring ApplicationContext 简介
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh(); // Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory); try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory); // Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory); // Initialize message source for this context.
initMessageSource(); // Initialize event multicaster for this context.
initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses.
onRefresh(); // Check for listener beans and register them.
registerListeners(); // Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event.
finishRefresh();
} catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
} // Destroy already created singletons to avoid dangling resources.
destroyBeans(); // Reset 'active' flag.
cancelRefresh(ex); // Propagate exception to caller.
throw ex;
} finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
prepareRefresh():准备需要刷新的资源。
/**
* Prepare this context for refreshing, setting its startup date and
* active flag as well as performing any initialization of property sources.
*/
protected void prepareRefresh() {
this.startupDate = System.currentTimeMillis(); //启动日期
this.closed.set(false); //激活标志
this.active.set(true); //激活标志 if (logger.isInfoEnabled()) {
logger.info("Refreshing " + this);
} // Initialize any placeholder property sources in the context environment
initPropertySources(); //供扩展使用 // Validate that all properties marked as required are resolvable
// see ConfigurablePropertyResolver#setRequiredProperties
getEnvironment().validateRequiredProperties(); // Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
this.earlyApplicationEvents = new LinkedHashSet<ApplicationEvent>();
}
class MyACTX extends ClassPathXmlApplicationContext { @Override
protected void initPropertySources() {
super.initPropertySources();
//TODO
}
}
/**
* Configure the factory's standard context characteristics,
* such as the context's ClassLoader and post-processors.
* @param beanFactory the BeanFactory to configure
*/
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
beanFactory.setBeanClassLoader(getClassLoader());
//表达式语言处理器,Spring3 SpEL表达式,#{xx.xx}支持。
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
//属性编辑器支持 如处理Date注入
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment())); // Configure the bean factory with context callbacks.
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
//忽略自动装配的接口
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
beanFactory.ignoreDependencyInterface(EnvironmentAware.class); // BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
//设置自动装配规则
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this); // Detect a LoadTimeWeaver and prepare for weaving, if found.
//AspectJ支持
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
} // Register default environment beans.
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());
}
}
SpEL:Spring Expression Language,运行时构造复杂表达式,存取对象图属性,对象方法调用等。SpEL为单独模块,只依赖于core模块。
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="driverClassName" value="${dataSource.driverClassName}"/>
<property name="url" value="${dataSource.url}"/>
<property name="username" value="${dataSource.username}"/>
<property name="password" value="${dataSource.password}"/>
<property name="maxActive" value="${dataSource.maxActive}"/>
<property name="minIdle" value="${dataSource.minIdle}" />
<property name="initialSize" value="${dataSource.initialSize}"></property>
<property name="validationQuery" value="${dataSource.validationQuery}"/>
</bean>
/**
* {@link BeanFactoryPostProcessor} implementation that allows for convenient
* registration of custom {@link PropertyEditor property editors}.
* 注册
*
*/
public class CustomEditorConfigurer implements BeanFactoryPostProcessor, Ordered { protected final Log logger = LogFactory.getLog(getClass()); private int order = Ordered.LOWEST_PRECEDENCE; // default: same as non-Ordered private PropertyEditorRegistrar[] propertyEditorRegistrars; private Map<Class<?>, Class<? extends PropertyEditor>> customEditors; ... ...
自定义Date属性编辑器MyDateEditor: class MyDateEditor extends PropertyEditorSupport { private String format = "yyyy-MM-dd"; public void setFormat(String format){
this.format = format;
} @Override
public void setAsText(String text) throws IllegalArgumentException {
SimpleDateFormat sp = new SimpleDateFormat(format);
try{
this.setValue(sp.parse(text));
} catch (ParseException e) {
e.printStackTrace();
}
}
} 配置:
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date">
<bean class="com.xxx.MyDateEditor">
<property name="format" value="yyyy-MM-dd HH:mm:ss"/>
</bean>
</entry>
</map>
</property>
</bean>
propertyEditorRegistrars:
自定义Date EditorRegister: class MyDateRegister implements PropertyEditorRegistrar{
private String format = "yyyy-MM-dd"; public void setFormat(String format){
this.format = format;
} @Override
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(format), true));
}
} 配置:
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="propertyEditorRegistrars">
<list>
<bean class="com.xxx.MyDateRegister">
<property name="format" value="yyyy-MM-dd HH:mm:ss"/>
</bean>
</list>
</property>
</bean>
<!-- 国际化资源文件 -->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<value>lang/message</value>
</property>
</bean>
读取:
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring/lang-resource.xml");
String msg = ctx.getMessage("xxx", null, Locale.CHINA);
System.out.println(msg);
nitApplicationEventMulticaster():
/**
* Add beans that implement ApplicationListener as listeners.
* Doesn't affect other listeners, which can be added without being beans.
*/
protected void registerListeners() {
// Register statically specified listeners first.
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
} // Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let post-processors apply to them!
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
} // Publish early application events now that we finally have a multicaster...
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (earlyEventsToProcess != null) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
... ...
Spring ApplicationContext 简介的更多相关文章
- Spring AOP 简介
Spring AOP 简介 如果说 IoC 是 Spring 的核心,那么面向切面编程就是 Spring 最为重要的功能之一了,在数据库事务中切面编程被广泛使用. AOP 即 Aspect Orien ...
- Spring Boot基础:Spring Boot简介与快速搭建(1)
1. Spring Boot简介 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化Spring应用的创建.运行.调试.部署等. Spring Boot默认使用tomca ...
- 1. Spring 框架简介及官方压缩包目录
一.Spring 框架简介及官方压缩包目录介绍 1.主要发明者:Rod Johnson 2.轮子理论推崇者: 2.1 轮子理论:不用重复发明轮子. 2.2 IT 行业:直接使用写好的代 ...
- Spring4- 01 - Spring框架简介及官方压缩包目录介绍- Spring IoC 的概念 - Spring hello world环境搭建
一. Spring 框架简介及官方压缩包目录介绍 主要发明者:Rod Johnson 轮子理论推崇者: 2.1 轮子理论:不用重复发明轮子. 2.2 IT 行业:直接使用写好的代码. Spring 框 ...
- Spring 系列: Spring 框架简介 -7个部分
Spring 系列: Spring 框架简介 Spring AOP 和 IOC 容器入门 在这由三部分组成的介绍 Spring 框架的系列文章的第一期中,将开始学习如何用 Spring 技术构建轻量级 ...
- Spring MVC简介
Spring MVC简介 Spring MVC框架是有一个MVC框架,通过实现Model-View-Controller模式来很好地将数据.业务与展现进行分离.从这样一个角度来说,Spring MVC ...
- 以静态变量保存 Spring ApplicationContext
package com.thinkgem.jeesite.common.utils; import java.net.HttpURLConnection; import java.net.URL; i ...
- Spring 系列: Spring 框架简介(转载)
Spring 系列: Spring 框架简介 http://www.ibm.com/developerworks/cn/java/wa-spring1/ Spring AOP 和 IOC 容器入门 在 ...
- Spring Boot简介
Spring Boot简介 Spring Boot是为了简化Spring开发而生,从Spring 3.x开始,Spring社区的发展方向就是弱化xml配置文件而加大注解的戏份.最近召开的SpringO ...
随机推荐
- String.format字符串拼接
一.String.Format1.简介 String类的format()方法用于创建格式化的字符串以及连接多个字符串对象. 2.参数 format()方法有两种重载形式. form ...
- UCOS阅读问题累积
1.#ifdef __cplusplus extern "C" { #endif 作用: 一般用于将C++代码以标准C形式输出(即以C的形式被调用),这是因为C++虽然常被认 ...
- CF1066B Heaters(贪心)
题意描述: Vova先生的家可以看作一个n×1的矩形,寒冷的冬天来了,Vova先生想让他的家里变得暖和起来.现在我们给你Vova先生家的平面图,其中111表示这个地方是加热炉,0表示这个地方什么也没有 ...
- 编程界失传秘术,SSO单点登录,什么是单点,如何实现登录?
单点登录 多系统,单一位置登录,实现多系统同时登录的一种技术. 常出现在互联网应用和企业级平台中. 如:京东. 单点登录一般是用于互相授信的系统,实现单一位置登录,全系统有效的. 三方登录:某系统,使 ...
- 10.安装使用jenkins及其插件
持续集成 1.安装jenkins 安装依赖 [root@git ~]# yum install java-1.8.0-openjdk java-1.8.0-openjdk-devel rpm包下载: ...
- CSS动画实例
上一篇讲过css动画transform transition的语法,这一节展示自己做的几个小例子加深印象 1. 线条动画效果 代码:最外层div包含2个小的div : a和b. a有左右边框(高度 ...
- OAuth2.0 与 oauth2-server 库的使用
作者:baiyi链接:https://www.jianshu.com/p/83b0f6d82d6c來源:简书 OAuth2.0 是关于授权的开放网络标准,它允许用户已第三方应用获取该用户在某一网站的私 ...
- python 解积分方程
引用:https://www.aliyun.com/jiaocheng/527786.html sympy求解极限.积分.微分.二元一次方程:http://www.gzhshoulu.wang/art ...
- python3 练习题100例 (五)
题目五:输入三个整数x,y,z,请把这三个数由小到大输出. #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 题目五: ...
- python三大器之while,if,for循环
一.for循环(遍历循环) 在Python你可能要经常遍历列表的所有元素,对每个元素执行相同的操作;对于包含数字的列表,可能要对每个元素进行相同的计算;在网站中,可能需要显示文章中的每个标题等等.某一 ...