承接前文Spring源码情操陶冶-AbstractApplicationContext#registerBeanPostProcessors
约定web.xml
配置的contextClass
为默认值XmlWebApplicationContext
瞧瞧官方注释
/**
* Initialize the MessageSource.
* Use parent's if none defined in this context.
*/
初始化MessageSource消息源,如果beanFactory不存在此bean则采用默认的配置并设置父类MessageSource
直接源码
protected void initMessageSource() {
//获取bean工厂,此处一般为DefaultListableBeanFactory
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
//首先判断是否已有xml文件定义了id为messageSource的bean对象
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
// Make MessageSource aware of parent MessageSource.
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
//为HierarchicalMessageSource的实现类
HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
//设置父类MessageSource,此处设置内部的parent messageSource
if (hms.getParentMessageSource() == null) {
hms.setParentMessageSource(getInternalParentMessageSource());
}
}
if (logger.isDebugEnabled()) {
logger.debug("Using MessageSource [" + this.messageSource + "]");
}
}
else {
// 则设置默认的DelegatingMessageSource 作为messageSource bean
DelegatingMessageSource dms = new DelegatingMessageSource();
dms.setParentMessageSource(getInternalParentMessageSource());
this.messageSource = dms;
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
if (logger.isDebugEnabled()) {
logger.debug("Unable to locate MessageSource with name '" + MESSAGE_SOURCE_BEAN_NAME +
"': using default [" + this.messageSource + "]");
}
}
}
小结
- 初始化资源配置,如果id为
messgeSource
的bean在spring xml文件中已配置,则需要注意其class属性为MessageSource的实现类;反之则默认设置DelegatingMessageSource单例资源配置类- 如果指定的messageSource类也为HierarchicalMessageSource的实现类则对其设置父类messageSource
- 此处只涉及到初始化,具体的用途后续补充
下节预告
Spring源码情操陶冶-AbstractApplicationContext#initApplicationEventMulticaster