IOC容器的初始化分爲三個過程實現:
- 第一個過程是Resource資源定位。這個Resouce指的是BeanDefinition的資源定位。這個過程就是容器找數據的過程,就像水桶裝水需要先找到水一樣。
- 第二個過程是BeanDefinition的載入過程。這個載入過程是把用戶定義好的Bean表示成Ioc容器內部的數據結構,而這個容器內部的數據結構就是BeanDefition。
- 第三個過程是向IOC容器註冊這些BeanDefinition的過程,這個過程就是將前面的BeanDefition保存到HashMap中的過程。
上面提到的過程一般是不包括Bean的依賴注入的實現。在Spring中,Bean的載入和依賴注入是兩個獨立的過程。依賴注入一般發生在應用第一次通過getBean向容器索取Bean的時候。下面的一張圖描述了這三個過程調用的主要方法,圖中的四個過程其實描述的是上面的第二個過程和第三個過程:
1 Resource定位
下面來看看主要的三個ApplicationContext的實現類是如何定位資源的,也就是找到我們通常所說“applicationContetx.xml”等配置文件的。
1.1 ClassPathXmlApplicationContext與FileSystemXmlApplicationContext
這兩個類都是非Web容器時,常用的ApplicationContext類。他們很相似,所有的構造方法都在重載調用一段核心的代碼。這段代碼雖然很短,但是其中是一個很複雜的執行過程,它完成了IOC容器的初始化。
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
這其中的setConfigLocations方法就是在進行資源定位。這個方法在AbstractRefreshableConfigApplicationContext類中實現。這個方法首先進行了非空了檢驗。這個Assert是Spring框架的一個工具類,這裏面進行了一個非空判斷。然後對這個路徑進行了一些處理。這樣就完成了資源的定位。這個定位其實就是使用者主動把配置文件的位置告訴Spring框架。
if (locations != null) {
Assert.noNullElements(locations, "Config locations must not be null");
this.configLocations = new String[locations.length];
for (int i = 0; i < locations.length; i++) {
this.configLocations[i] = resolvePath(locations[i]).trim();
}
}
else {
this.configLocations = null;
}
1.2 XmlWebApplicationContext
這個類是web容器初始化spring IOC容器的類。對於web應用來說,我們通常是不是直接去初始化這個容器的,它的裝載是一個自動進行的過程。這是因爲我們在web.xml中配置了這樣一句話,這其實就是spring的入口
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
(1)下面來看這個類ContextLoaderListener,從它的定義就能看出,這是一個ServletContextListener,它的核心方法就是下面的contextInitialized事件,也就是當web容器初始化的時候,spring容器也進行了初始化。
public class ContextLoaderListener extends ContextLoader implements ServletContextListener
/**
* Initialize the root web application context.
*/
@Override
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}
這個方法將servletContext作爲參數傳入,它的目標就是爲了讀取web.xml配置文件,找到我們對spring的配置。(2)下面來看initWebApplicationContext方法,它完成了對webApplictionContext的初始化工作。這個方法裏的有比較重要的幾段代碼,他們主要完成了webAppliction構建,參數的注入,以及保存
- 構建webApplictionContext
if (this.context == null) {
this.context = createWebApplicationContext(servletContext);
}
這段代碼看字面意思就知道是新建了一個webApplicationContext。它是由一個工具類產生一個新的wac,這個方法中調用了determineContextClass方法,它決定了容器初始化爲哪種類型的ApplicationContext,因爲我們可以在web.xml中對這種類型進行指定。而如果沒有指定的話,就將使用默認的XmlWebApplicationContext。
protected Class<?> determineContextClass(ServletContext servletContext) {
String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
if (contextClassName != null) {
try {
return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Failed to load custom context class [" + contextClassName + "]", ex);
}
}
else {
contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
try {
return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Failed to load default context class [" + contextClassName + "]", ex);
}
}
}
- 注入參數,初始化這個空的容器 。這個過程的入口是configureAndRefreshWebApplicationContext這個方法中完成了wac的Id設置,將servletContext注入到wac中,還有最重要的方法,就是setConfigLocation.這裏從web.xml中尋找指定的配置文件的位置,也就是我們通常配置的“contextConfigLocation”屬性
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
wac.setConfigLocation(configLocationParam);
}
那麼如果沒有指定呢?在XMLWebApplicationContext中這樣一些常量,他們表示了配置文件的默認位置
/** Default config location for the root context */
public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml";
/** Default prefix for building a config location for a namespace */
public static final String DEFAULT_CONFIG_LOCATION_PREFIX = "/WEB-INF/";
/** Default suffix for building a config location for a namespace */
public static final String DEFAULT_CONFIG_LOCATION_SUFFIX = ".xml";
- spring容器初始化完成後,放入serverletContext中,這樣在web容器中就可以拿到applicationContext
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
2 BeanDefinition載入
這個過程是最繁瑣,也是最重要的一個過程。這一個過程分爲以下幾步,
- 構造一個BeanFactory,也就是IOC容器
- 調用XML解析器得到document對象
- 按照Spring的規則解析BeanDefition
對於以上過程,都需要一個入口,也就是前面提到的refresh()方法,這個方法AbstractApplicationContext類中,它描述了整個ApplicationContext的初始化過程,比如BeanFactory的更新,MessgaeSource和PostProcessor的註冊等等。它更像是個初始化的提綱,這個過程爲Bean的聲明週期管理提供了條件。
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) {
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;
}
}
}
2.1 構建IOC容器
這個過程的入口是refresh方法中的obtainFreshBeanFactory()方法。整個過程構建了一個DefaultListableBeanFactory對象,這也就是IOC容器的實際類型。這一過程的核心如下:
2.1.1 obtainFreshBeanFactory
這個方法的作用是通知子類去初始化ioc容器,它調用了AbstractRefreshableApplicationContext的refreshBeanFactory 方法 進行後續工作。同時在日誌是debug模式的時候,向日志輸出初始化結果。
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}
2.1.2 refreshBeanFactory
這個方法在創建IOC容器前,如果已經有容器存在,那麼需要將已有的容器關閉和銷燬,保證refresh之後使用的是新建立的容器。同時 在創建了空的IOC容器後,開始了對BeanDefitions的載入
protected final void refreshBeanFactory() throws BeansException {
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
DefaultListableBeanFactory beanFactory = createBeanFactory();//創建了IOC容器
beanFactory.setSerializationId(getId());
customizeBeanFactory(beanFactory);
loadBeanDefinitions(beanFactory);// 啓動對BeanDefitions的載入
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
protected DefaultListableBeanFactory createBeanFactory() {
return new DefaultListableBeanFactory(getInternalParentBeanFactory());
}
2.2 解析XML文件
對於Spring,我們通常使用xml形式的配置文件定義Bean,在對BeanDefition載入之前,首先需要進行的就是XML文件的解析。整個過程的核心方法如下:
2.2.1 loadBeanDefinitions(DefaultListableBeanFactory beanFactory)
這裏構造一個XmlBeanDefinitionReader對象,把解析工作交給他去實現
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// 定義一個XmlBeanDefinitionReader對象 用於解析XML
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
//進行一些初始化和環境配置
// Configure the bean definition reader with this context's
// resource loading environment.
beanDefinitionReader.setEnvironment(this.getEnvironment());
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
initBeanDefinitionReader(beanDefinitionReader);
//解析入口
loadBeanDefinitions(beanDefinitionReader);
}
2.2.2 loadBeanDefinitions
(1) AbstractXmlApplicationContext類 ,利用reader的方法解析,向下調用(Load the bean definitions with the given XmlBeanDefinitionReader.)
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
Resource[] configResources = getConfigResources();
if (configResources != null) {
reader.loadBeanDefinitions(configResources);
}
String[] configLocations = getConfigLocations();
if (configLocations != null) {
reader.loadBeanDefinitions(configLocations);
}
}
(2) AbstractBeanDefinitionReader 類 解析Resource 向下調用public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
Assert.notNull(resources, "Resource array must not be null");
int counter = 0;
for (Resource resource : resources) {
counter += loadBeanDefinitions(resource);
}
return counter;
}
(3) XmlBeanDefinitionReader
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
return loadBeanDefinitions(new EncodedResource(resource));
}
在下面方法得到了XML文件,並打開IO流,準備進行解析。實際向下調用public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
Assert.notNull(encodedResource, "EncodedResource must not be null");
if (logger.isInfoEnabled()) {
logger.info("Loading XML bean definitions from " + encodedResource.getResource());
}
Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
if (currentResources == null) {
currentResources = new HashSet<EncodedResource>(4);
this.resourcesCurrentlyBeingLoaded.set(currentResources);
}
if (!currentResources.add(encodedResource)) {
throw new BeanDefinitionStoreException(
"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
}
try {
InputStream inputStream = encodedResource.getResource().getInputStream();
try {
InputSource inputSource = new InputSource(inputStream);
if (encodedResource.getEncoding() != null) {
inputSource.setEncoding(encodedResource.getEncoding());
}
return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
}
finally {
inputStream.close();
}
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(
"IOException parsing XML document from " + encodedResource.getResource(), ex);
}
finally {
currentResources.remove(encodedResource);
if (currentResources.isEmpty()) {
this.resourcesCurrentlyBeingLoaded.remove();
}
}
}
(4) doLoadBeanDefinitions
下面是它的核心方法,第一句調用Spring解析XML的方法得到document對象,而第二句則是載入BeanDefitions的入口
try {
Document doc = doLoadDocument(inputSource, resource);
return registerBeanDefinitions(doc, resource);
}
2.3 解析Spring數據結構
這一步是將document對象解析成spring內部的bean結構,實際上是AbstractBeanDefinition對象。這個對象的解析結果放入BeanDefinitionHolder中,而整個過程是由BeanDefinitionParserDelegate完成。
2.3.1 registerBeanDefinitions
解析BeanDefinitions的入口,向下調用doRegisterBeanDefinitions方法
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
this.readerContext = readerContext;
logger.debug("Loading bean definitions");
Element root = doc.getDocumentElement();
doRegisterBeanDefinitions(root);
}
2.3.2 doRegisterBeanDefinitions
定義了BeanDefinitionParserDelegate 解析處理器對象,向下調用parseBeanDefinitions 方法
protected void doRegisterBeanDefinitions(Element root) {
// Any nested <beans> elements will cause recursion in this method. In
// order to propagate and preserve <beans> default-* attributes correctly,
// keep track of the current (parent) delegate, which may be null. Create
// the new (child) delegate with a reference to the parent for fallback purposes,
// then ultimately reset this.delegate back to its original (parent) reference.
// this behavior emulates a stack of delegates without actually necessitating one.
BeanDefinitionParserDelegate parent = this.delegate;
this.delegate = createDelegate(getReaderContext(), root, parent);
if (this.delegate.isDefaultNamespace(root)) {
String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
if (StringUtils.hasText(profileSpec)) {
String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
return;
}
}
}
preProcessXml(root);
parseBeanDefinitions(root, this.delegate);
postProcessXml(root);
this.delegate = parent;
}
2.3.3 parseBeanDefinitions
從document對象的根節點開始,依據不同類型解析。具體調用parseDefaultElement和parseCustomElement兩個方法進行解析。這個主要的區別是因爲bean的命名空間可能不同,Spring的默認命名空間是“http://www.springframework.org/schema/beans”,如果不是這個命名空間中定義的bean,將使用parseCustomElement方法。
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
if (delegate.isDefaultNamespace(root)) {
NodeList nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element ele = (Element) node;
if (delegate.isDefaultNamespace(ele)) {
parseDefaultElement(ele, delegate);
}
else {
delegate.parseCustomElement(ele);
}
}
}
}
else {
delegate.parseCustomElement(root);
}
}
2.3.4 parseDefaultElement
這個方法就是根據bean的類型進行不同的方法解析。
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
//解析import
if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
importBeanDefinitionResource(ele);
}
//解析alias
else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
processAliasRegistration(ele);
}
//解析普通的bean
else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
processBeanDefinition(ele, delegate);
}
//解析beans 遞歸返回
else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
// recurse
doRegisterBeanDefinitions(ele);
}
}
2.3.5 processBeanDefinition
這個方法完成對普通,也是最常見的Bean的解析。這個方法實際上完成了解析和註冊兩個過程。這兩個過程分別向下調用parseBeanDefinitionElement和registerBeanDefinition方法。
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
//定義BeanDefinitionHolder對象 ,完成解析的對象存放在這個對象裏面
BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
if (bdHolder != null) {
bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
try {
// 向容器註冊解析完成的Bean
BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error("Failed to register bean definition with name '" +
bdHolder.getBeanName() + "'", ele, ex);
}
// Send registration event.
getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
}
}
2.3.6 parseBeanDefinitionElement
定義在BeanDefinitionParserDelegate 類中,完成了BeanDefition解析工作。在這裏可以看到,AbstractBeanDefinition實際上spring的內部保存的數據結構
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) {
String id = ele.getAttribute(ID_ATTRIBUTE);
String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
List<String> aliases = new ArrayList<String>();
if (StringUtils.hasLength(nameAttr)) {
String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
aliases.addAll(Arrays.asList(nameArr));
}
String beanName = id;
if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
beanName = aliases.remove(0);
if (logger.isDebugEnabled()) {
logger.debug("No XML 'id' specified - using '" + beanName +
"' as bean name and " + aliases + " as aliases");
}
}
if (containingBean == null) {
checkNameUniqueness(beanName, aliases, ele);
}
AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
if (beanDefinition != null) {
if (!StringUtils.hasText(beanName)) {
try {
if (containingBean != null) {
beanName = BeanDefinitionReaderUtils.generateBeanName(
beanDefinition, this.readerContext.getRegistry(), true);
}
else {
beanName = this.readerContext.generateBeanName(beanDefinition);
// Register an alias for the plain bean class name, if still possible,
// if the generator returned the class name plus a suffix.
// This is expected for Spring 1.2/2.0 backwards compatibility.
String beanClassName = beanDefinition.getBeanClassName();
if (beanClassName != null &&
beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() &&
!this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
aliases.add(beanClassName);
}
}
if (logger.isDebugEnabled()) {
logger.debug("Neither XML 'id' nor 'name' specified - " +
"using generated bean name [" + beanName + "]");
}
}
catch (Exception ex) {
error(ex.getMessage(), ele);
return null;
}
}
String[] aliasesArray = StringUtils.toStringArray(aliases);
return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
}
return null;
}
/**
* Parse the bean definition itself, without regard to name or aliases. May return
* {@code null} if problems occurred during the parsing of the bean definition.
*/
public AbstractBeanDefinition parseBeanDefinitionElement(
Element ele, String beanName, BeanDefinition containingBean) {
this.parseState.push(new BeanEntry(beanName));
String className = null;
if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
}
try {
String parent = null;
if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
parent = ele.getAttribute(PARENT_ATTRIBUTE);
}
AbstractBeanDefinition bd = createBeanDefinition(className, parent);
parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
parseMetaElements(ele, bd);
parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
parseConstructorArgElements(ele, bd);
parsePropertyElements(ele, bd);
parseQualifierElements(ele, bd);
bd.setResource(this.readerContext.getResource());
bd.setSource(extractSource(ele));
return bd;
}
catch (ClassNotFoundException ex) {
error("Bean class [" + className + "] not found", ele, ex);
}
catch (NoClassDefFoundError err) {
error("Class that bean class [" + className + "] depends on not found", ele, err);
}
catch (Throwable ex) {
error("Unexpected failure during bean definition parsing", ele, ex);
}
finally {
this.parseState.pop();
}
return null;
}
2.4 註冊BeanDefition
完成了上面的三步後,目前ApplicationContext中有兩種類型的結構,一個是DefaultListableBeanFactory,它是Spring IOC容器,另一種是若干個BeanDefinitionHolder,這裏麪包含實際的Bean對象,AbstractBeanDefition。
需要把二者關聯起來,這樣Spring才能對Bean進行管理。在DefaultListableBeanFactory中定義了一個Map對象,保存所有的BeanDefition。這個註冊的過程就是把前面解析得到的Bean放入這個Map的過程。
/** Map of bean definition objects, keyed by bean name */
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<String, BeanDefinition>(64);
2.4.1 registerBeanDefinition
註冊的入口,對於普通的Bean和Alias調用不同類型的註冊方法進行註冊。
public static void registerBeanDefinition(
BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
throws BeanDefinitionStoreException {
// Register bean definition under primary name.
String beanName = definitionHolder.getBeanName();
registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
// Register aliases for bean name, if any.
String[] aliases = definitionHolder.getAliases();
if (aliases != null) {
for (String alias : aliases) {
registry.registerAlias(beanName, alias);
}
}
}
2.4.2 registerBeanDefinition
註冊Bean 定義在DefaultListableBeanFactory中
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException {
//非空斷言
Assert.hasText(beanName, "Bean name must not be empty");
Assert.notNull(beanDefinition, "BeanDefinition must not be null");
if (beanDefinition instanceof AbstractBeanDefinition) {
try {
((AbstractBeanDefinition) beanDefinition).validate();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
"Validation of bean definition failed", ex);
}
}
BeanDefinition oldBeanDefinition;
oldBeanDefinition = this.beanDefinitionMap.get(beanName);
//同名檢測
if (oldBeanDefinition != null) {
//是否能夠覆蓋檢測
if (!this.allowBeanDefinitionOverriding) {
throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
"Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +
"': There is already [" + oldBeanDefinition + "] bound.");
}
else if (oldBeanDefinition.getRole() < beanDefinition.getRole()) {
// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
if (this.logger.isWarnEnabled()) {
this.logger.warn("Overriding user-defined bean definition for bean '" + beanName +
" with a framework-generated bean definition ': replacing [" +
oldBeanDefinition + "] with [" + beanDefinition + "]");
}
}
else {
if (this.logger.isInfoEnabled()) {
this.logger.info("Overriding bean definition for bean '" + beanName +
"': replacing [" + oldBeanDefinition + "] with [" + beanDefinition + "]");
}
}
}
else {
this.beanDefinitionNames.add(beanName);
this.manualSingletonNames.remove(beanName);
this.frozenBeanDefinitionNames = null;
}
//放入Map中
this.beanDefinitionMap.put(beanName, beanDefinition);
if (oldBeanDefinition != null || containsSingleton(beanName)) {
resetBeanDefinition(beanName);
}
}
2.4.3 registerAlias
定義在SimpleAliasRegistry類,對別名進行註冊
public void registerAlias(String name, String alias) {
Assert.hasText(name, "'name' must not be empty");
Assert.hasText(alias, "'alias' must not be empty");
if (alias.equals(name)) {
this.aliasMap.remove(alias);
}
else {
if (!allowAliasOverriding()) {
String registeredName = this.aliasMap.get(alias);
if (registeredName != null && !registeredName.equals(name)) {
throw new IllegalStateException("Cannot register alias '" + alias + "' for name '" +
name + "': It is already registered for name '" + registeredName + "'.");
}
}
checkForAliasCircle(name, alias);
this.aliasMap.put(alias, name);
}
}