本文只做記錄,會帶來不好的閱讀體驗,請慎重矩父!
IOC(Inversion Of Control) 控制反轉:
??所謂的控制反轉,就是把代碼里需要實現(xiàn)對象創(chuàng)建排霉、依賴的代碼窍株,反轉給容器來實現(xiàn)。
DI(Dependency Injection)依賴注入:
??對象被動接受依賴類不需要自己實例或者尋找攻柠,簡單來說就是對象不是從容器中查找它依賴的類球订,而是在容器實例化對象的時候主動將其依賴的類注入。
IOC設計視角:
1.對象和對象的關系如何表示瑰钮?
答:xml冒滩、properties文件等語義化配置文件表示者娱。
2.描述對象關系的文件存儲在什么地方残邀?
答:classpath、filesystem鞭呕、URL網絡資源苟耻、servletContext等篇恒。
3.不同的配置文件對對象的描述不一樣,如標準的凶杖,自定義聲明式胁艰,如何統(tǒng)一?
答:對象定義需要統(tǒng)一智蝠,所有外部的描述都必須轉化成統(tǒng)一的描述定義腾么。
4.如何對不同的配置文件進行解析?
答:針對不同的文件配置語法杈湾,采用不同的解析器解虱。
Spring核心容器圖
1.BeanFactory
??Spring中Bean的創(chuàng)建是典型的工廠模式,IOC容器提供了管理對象之間依賴關系的服務毛秘,在Spring中有許多IOC容器的實現(xiàn)提供給開發(fā)者使用,其相互關系如圖:
??其中BeanFactory作為最頂層的接口類,它定義了IOC容器的基本功能規(guī)范叫挟,BeanFactory有三個重要的子類:
ListableBeanFactory艰匙、HierarchaicalBeanFactory、AutowireCapableBeanFactory
但是從類圖中看出最終實現(xiàn)的是 DefaultListableBeanFactory抹恳,它實現(xiàn)了所有接口员凝。
為什么要定義這么多層次的接口?
??每個接口都有它的使用的場合奋献,它主要是為了區(qū)分在Spring內部在操作過程中區(qū)分每個對象傳遞和轉換過程健霹,對對象的數(shù)據(jù)訪問鎖做的限制。
例如:ListableBeanFactory接口表示這些Bean是可列表化的瓶蚂,而HierarchicalBeanFactory表示這些Bean是有繼承關系的糖埋,也就是這些Bean有可能有父Bean。AutowireCapableBeanFactory接口定義了Bean的自動裝配規(guī)則窃这。這三個接口共同定義了Bean的集合瞳别、Bean之間的關系、以及Bean行為杭攻。
看一下最基礎的BeanFactory源碼:
/**
* The root interface for accessing a Spring bean container.
* This is the basic client view of a bean container;
* further interfaces such as {@link ListableBeanFactory} and
* {@link org.springframework.beans.factory.config.ConfigurableBeanFactory}
* are available for specific purposes.
*
* <p>This interface is implemented by objects that hold a number of bean definitions,
* each uniquely identified by a String name. Depending on the bean definition,
* the factory will return either an independent instance of a contained object
* (the Prototype design pattern), or a single shared instance (a superior
* alternative to the Singleton design pattern, in which the instance is a
* singleton in the scope of the factory). Which type of instance will be returned
* depends on the bean factory configuration: the API is the same. Since Spring
* 2.0, further scopes are available depending on the concrete application
* context (e.g. "request" and "session" scopes in a web environment).
*
* <p>The point of this approach is that the BeanFactory is a central registry
* of application components, and centralizes configuration of application
* components (no more do individual objects need to read properties files,
* for example). See chapters 4 and 11 of "Expert One-on-One J2EE Design and
* Development" for a discussion of the benefits of this approach.
*
* <p>Note that it is generally better to rely on Dependency Injection
* ("push" configuration) to configure application objects through setters
* or constructors, rather than use any form of "pull" configuration like a
* BeanFactory lookup. Spring's Dependency Injection functionality is
* implemented using this BeanFactory interface and its subinterfaces.
*
* <p>Normally a BeanFactory will load bean definitions stored in a configuration
* source (such as an XML document), and use the {@code org.springframework.beans}
* package to configure the beans. However, an implementation could simply return
* Java objects it creates as necessary directly in Java code. There are no
* constraints on how the definitions could be stored: LDAP, RDBMS, XML,
* properties file, etc. Implementations are encouraged to support references
* amongst beans (Dependency Injection).
*
* <p>In contrast to the methods in {@link ListableBeanFactory}, all of the
* operations in this interface will also check parent factories if this is a
* {@link HierarchicalBeanFactory}. If a bean is not found in this factory instance,
* the immediate parent factory will be asked. Beans in this factory instance
* are supposed to override beans of the same name in any parent factory.
*
* <p>Bean factory implementations should support the standard bean lifecycle interfaces
* as far as possible. The full set of initialization methods and their standard order is:
* <ol>
* <li>BeanNameAware's {@code setBeanName}
* <li>BeanClassLoaderAware's {@code setBeanClassLoader}
* <li>BeanFactoryAware's {@code setBeanFactory}
* <li>EnvironmentAware's {@code setEnvironment}
* <li>EmbeddedValueResolverAware's {@code setEmbeddedValueResolver}
* <li>ResourceLoaderAware's {@code setResourceLoader}
* (only applicable when running in an application context)
* <li>ApplicationEventPublisherAware's {@code setApplicationEventPublisher}
* (only applicable when running in an application context)
* <li>MessageSourceAware's {@code setMessageSource}
* (only applicable when running in an application context)
* <li>ApplicationContextAware's {@code setApplicationContext}
* (only applicable when running in an application context)
* <li>ServletContextAware's {@code setServletContext}
* (only applicable when running in a web application context)
* <li>{@code postProcessBeforeInitialization} methods of BeanPostProcessors
* <li>InitializingBean's {@code afterPropertiesSet}
* <li>a custom init-method definition
* <li>{@code postProcessAfterInitialization} methods of BeanPostProcessors
* </ol>
*
* <p>On shutdown of a bean factory, the following lifecycle methods apply:
* <ol>
* <li>{@code postProcessBeforeDestruction} methods of DestructionAwareBeanPostProcessors
* <li>DisposableBean's {@code destroy}
* <li>a custom destroy-method definition
* </ol>
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Chris Beams
* @since 13 April 2001
* @see BeanNameAware#setBeanName
* @see BeanClassLoaderAware#setBeanClassLoader
* @see BeanFactoryAware#setBeanFactory
* @see org.springframework.context.ResourceLoaderAware#setResourceLoader
* @see org.springframework.context.ApplicationEventPublisherAware#setApplicationEventPublisher
* @see org.springframework.context.MessageSourceAware#setMessageSource
* @see org.springframework.context.ApplicationContextAware#setApplicationContext
* @see org.springframework.web.context.ServletContextAware#setServletContext
* @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization
* @see InitializingBean#afterPropertiesSet
* @see org.springframework.beans.factory.support.RootBeanDefinition#getInitMethodName
* @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization
* @see DisposableBean#destroy
* @see org.springframework.beans.factory.support.RootBeanDefinition#getDestroyMethodName
*/
public interface BeanFactory {
/**
* Used to dereference a {@link FactoryBean} instance and distinguish it from
* beans <i>created</i> by the FactoryBean. For example, if the bean named
* {@code myJndiObject} is a FactoryBean, getting {@code &myJndiObject}
* will return the factory, not the instance returned by the factory.
*/
//對FactoryBean的轉義定義祟敛,因為如果使用bean的名字檢索FactoryBean得到的對象是工廠生成的對象,
//如果需要得到工廠本身兆解,需要轉義
String FACTORY_BEAN_PREFIX = "&";
/**
* Return an instance, which may be shared or independent, of the specified bean.
* <p>This method allows a Spring BeanFactory to be used as a replacement for the
* Singleton or Prototype design pattern. Callers may retain references to
* returned objects in the case of Singleton beans.
* <p>Translates aliases back to the corresponding canonical bean name.
* Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to retrieve
* @return an instance of the bean
* @throws NoSuchBeanDefinitionException if there is no bean definition
* with the specified name
* @throws BeansException if the bean could not be obtained
*/
//根據(jù)bean的名字馆铁,獲取在IOC容器中得到bean實例
Object getBean(String name) throws BeansException;
/**
* Return an instance, which may be shared or independent, of the specified bean.
* <p>Behaves the same as {@link #getBean(String)}, but provides a measure of type
* safety by throwing a BeanNotOfRequiredTypeException if the bean is not of the
* required type. This means that ClassCastException can't be thrown on casting
* the result correctly, as can happen with {@link #getBean(String)}.
* <p>Translates aliases back to the corresponding canonical bean name.
* Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to retrieve
* @param requiredType type the bean must match. Can be an interface or superclass
* of the actual class, or {@code null} for any match. For example, if the value
* is {@code Object.class}, this method will succeed whatever the class of the
* returned instance.
* @return an instance of the bean
* @throws NoSuchBeanDefinitionException if there is no such bean definition
* @throws BeanNotOfRequiredTypeException if the bean is not of the required type
* @throws BeansException if the bean could not be created
*/
//根據(jù)bean的名字和Class類型來得到bean實例,增加了類型安全驗證機制锅睛。
<T> T getBean(String name, @Nullable Class<T> requiredType) throws BeansException;
/**
* Return an instance, which may be shared or independent, of the specified bean.
* <p>Allows for specifying explicit constructor arguments / factory method arguments,
* overriding the specified default arguments (if any) in the bean definition.
* @param name the name of the bean to retrieve
* @param args arguments to use when creating a bean instance using explicit arguments
* (only applied when creating a new instance as opposed to retrieving an existing one)
* @return an instance of the bean
* @throws NoSuchBeanDefinitionException if there is no such bean definition
* @throws BeanDefinitionStoreException if arguments have been given but
* the affected bean isn't a prototype
* @throws BeansException if the bean could not be created
* @since 2.5
*/
Object getBean(String name, Object... args) throws BeansException;
/**
* Return the bean instance that uniquely matches the given object type, if any.
* <p>This method goes into {@link ListableBeanFactory} by-type lookup territory
* but may also be translated into a conventional by-name lookup based on the name
* of the given type. For more extensive retrieval operations across sets of beans,
* use {@link ListableBeanFactory} and/or {@link BeanFactoryUtils}.
* @param requiredType type the bean must match; can be an interface or superclass.
* {@code null} is disallowed.
* @return an instance of the single bean matching the required type
* @throws NoSuchBeanDefinitionException if no bean of the given type was found
* @throws NoUniqueBeanDefinitionException if more than one bean of the given type was found
* @throws BeansException if the bean could not be created
* @since 3.0
* @see ListableBeanFactory
*/
<T> T getBean(Class<T> requiredType) throws BeansException;
/**
* Return an instance, which may be shared or independent, of the specified bean.
* <p>Allows for specifying explicit constructor arguments / factory method arguments,
* overriding the specified default arguments (if any) in the bean definition.
* <p>This method goes into {@link ListableBeanFactory} by-type lookup territory
* but may also be translated into a conventional by-name lookup based on the name
* of the given type. For more extensive retrieval operations across sets of beans,
* use {@link ListableBeanFactory} and/or {@link BeanFactoryUtils}.
* @param requiredType type the bean must match; can be an interface or superclass.
* {@code null} is disallowed.
* @param args arguments to use when creating a bean instance using explicit arguments
* (only applied when creating a new instance as opposed to retrieving an existing one)
* @return an instance of the bean
* @throws NoSuchBeanDefinitionException if there is no such bean definition
* @throws BeanDefinitionStoreException if arguments have been given but
* the affected bean isn't a prototype
* @throws BeansException if the bean could not be created
* @since 4.1
*/
<T> T getBean(Class<T> requiredType, Object... args) throws BeansException;
/**
* Does this bean factory contain a bean definition or externally registered singleton
* instance with the given name?
* <p>If the given name is an alias, it will be translated back to the corresponding
* canonical bean name.
* <p>If this factory is hierarchical, will ask any parent factory if the bean cannot
* be found in this factory instance.
* <p>If a bean definition or singleton instance matching the given name is found,
* this method will return {@code true} whether the named bean definition is concrete
* or abstract, lazy or eager, in scope or not. Therefore, note that a {@code true}
* return value from this method does not necessarily indicate that {@link #getBean}
* will be able to obtain an instance for the same name.
* @param name the name of the bean to query
* @return whether a bean with the given name is present
*/
//提供對bean的檢索埠巨,看看是否在IOC容器有這個名字的bean
boolean containsBean(String name);
/**
* Is this bean a shared singleton? That is, will {@link #getBean} always
* return the same instance?
* <p>Note: This method returning {@code false} does not clearly indicate
* independent instances. It indicates non-singleton instances, which may correspond
* to a scoped bean as well. Use the {@link #isPrototype} operation to explicitly
* check for independent instances.
* <p>Translates aliases back to the corresponding canonical bean name.
* Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to query
* @return whether this bean corresponds to a singleton instance
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @see #getBean
* @see #isPrototype
*/
//根據(jù)bean名字得到bean實例,并同時判斷這個bean是不是單例
boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
/**
* Is this bean a prototype? That is, will {@link #getBean} always return
* independent instances?
* <p>Note: This method returning {@code false} does not clearly indicate
* a singleton object. It indicates non-independent instances, which may correspond
* to a scoped bean as well. Use the {@link #isSingleton} operation to explicitly
* check for a shared singleton instance.
* <p>Translates aliases back to the corresponding canonical bean name.
* Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to query
* @return whether this bean will always deliver independent instances
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 2.0.3
* @see #getBean
* @see #isSingleton
*/
boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
/**
* Check whether the bean with the given name matches the specified type.
* More specifically, check whether a {@link #getBean} call for the given name
* would return an object that is assignable to the specified target type.
* <p>Translates aliases back to the corresponding canonical bean name.
* Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to query
* @param typeToMatch the type to match against (as a {@code ResolvableType})
* @return {@code true} if the bean type matches,
* {@code false} if it doesn't match or cannot be determined yet
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 4.2
* @see #getBean
* @see #getType
*/
boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;
/**
* Check whether the bean with the given name matches the specified type.
* More specifically, check whether a {@link #getBean} call for the given name
* would return an object that is assignable to the specified target type.
* <p>Translates aliases back to the corresponding canonical bean name.
* Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to query
* @param typeToMatch the type to match against (as a {@code Class})
* @return {@code true} if the bean type matches,
* {@code false} if it doesn't match or cannot be determined yet
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 2.0.1
* @see #getBean
* @see #getType
*/
boolean isTypeMatch(String name, @Nullable Class<?> typeToMatch) throws NoSuchBeanDefinitionException;
/**
* Determine the type of the bean with the given name. More specifically,
* determine the type of object that {@link #getBean} would return for the given name.
* <p>For a {@link FactoryBean}, return the type of object that the FactoryBean creates,
* as exposed by {@link FactoryBean#getObjectType()}.
* <p>Translates aliases back to the corresponding canonical bean name.
* Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to query
* @return the type of the bean, or {@code null} if not determinable
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 1.1.2
* @see #getBean
* @see #isTypeMatch
*/
//得到bean實例的Class類型
@Nullable
Class<?> getType(String name) throws NoSuchBeanDefinitionException;
/**
* Return the aliases for the given bean name, if any.
* All of those aliases point to the same bean when used in a {@link #getBean} call.
* <p>If the given name is an alias, the corresponding original bean name
* and other aliases (if any) will be returned, with the original bean name
* being the first element in the array.
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the bean name to check for aliases
* @return the aliases, or an empty array if none
* @see #getBean
*/
//得到bean的別名衣撬,如果根據(jù)別名檢索乖订,那么其原名也會被檢索出來
String[] getAliases(String name);
}
??在BeanFactory里只對IOC容器的基本行為進行定義,根本不關心你的Bean是如何加載的具练。正如我們只關心工廠能生產什么對象乍构,至于工廠是如何生成對象我們是無須關心。
??如果要知道IOC如如何產生對象的扛点,我們具體要看看IOC容器的實現(xiàn)哥遮,Spring提供了許多IOC容器的實現(xiàn)。
比如:GenericApplicationContext陵究、ClassPathXmlApplicationContext等
??ApplicationContext是Spring提供的一個高級IOC容器眠饮,它除了能夠提供IOC容器的基本功能,還為了用于提供以下附加服務铜邮。
1.支持信息源仪召,可實現(xiàn)國際化寨蹋。(實現(xiàn)MessageSource接口)
2.訪問資源。(實現(xiàn)ResourcePatternResolver接口)
3.支持應用事件扔茅。(實現(xiàn)ApplicationEventPublisher接口)
2.BeanDefinition
??SpringIOC容器管理了我們定義的各種Bean對象及其相互關系已旧,Bean對象在Spring實現(xiàn)是以BeanDefinition來描述的,其繼承體系如下:
3.BeanDefinitionReader
??Bean的解析過程非常復雜召娜,功能劃分很細运褪,因為這里需要被擴展的地方太多了,必須保證靈活性玖瘸,以應對可能的變化秸讹。Bean的解析主要就是對Spring配置文件的解析。這個解析的過程主要通過BeanDefinitionReader來完成雅倒,最后看看Spring中BeanDefinitionReader類的結構圖:
現(xiàn)在我們已經對IOC容器有了基本的了解了璃诀。
WEB IOC容器初體驗
??還是從大家熟悉的DispatcherServlet開始,我們最先想到的還是DispathcherServlet的init()方法屯断。在DispatcherServlet中并沒有找到init()方法文虏。但是經過探索,往上追索在其父類HttpServletBean中找到了init()方法:
/**
* Map config parameters onto bean properties of this servlet, and
* invoke subclass initialization.
* @throws ServletException if bean properties are invalid (or required
* properties are missing), or if subclass initialization fails.
*/
@Override
public final void init() throws ServletException {
if (logger.isDebugEnabled()) {
logger.debug("Initializing servlet '" + getServletName() + "'");
}
// Set bean properties from init parameters.
PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
if (!pvs.isEmpty()) {
try {
//定位資源
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
//加載配置信息
ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
initBeanWrapper(bw);
bw.setPropertyValues(pvs, true);
}
catch (BeansException ex) {
if (logger.isErrorEnabled()) {
logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
}
throw ex;
}
}
// Let subclasses do whatever initialization they like.
initServletBean();
if (logger.isDebugEnabled()) {
logger.debug("Servlet '" + getServletName() + "' configured successfully");
}
}
??在init()方法中殖演,真正完成初始化容器動作的邏輯其實在initServletBean(); 繼續(xù)跟進initServletBean()代碼在FrameworkServlet類中:
/**
* Overridden method of {@link HttpServletBean}, invoked after any bean properties
* have been set. Creates this servlet's WebApplicationContext.
*/
@Override
protected final void initServletBean() throws ServletException {
getServletContext().log("Initializing Spring FrameworkServlet '" + getServletName() + "'");
if (this.logger.isInfoEnabled()) {
this.logger.info("FrameworkServlet '" + getServletName() + "': initialization started");
}
long startTime = System.currentTimeMillis();
try {
this.webApplicationContext = initWebApplicationContext();
initFrameworkServlet();
}
catch (ServletException ex) {
this.logger.error("Context initialization failed", ex);
throw ex;
}
catch (RuntimeException ex) {
this.logger.error("Context initialization failed", ex);
throw ex;
}
if (this.logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
this.logger.info("FrameworkServlet '" + getServletName() + "': initialization completed in " +
elapsedTime + " ms");
}
}
/**
* Initialize and publish the WebApplicationContext for this servlet.
* <p>Delegates to {@link #createWebApplicationContext} for actual creation
* of the context. Can be overridden in subclasses.
* @return the WebApplicationContext instance
* @see #FrameworkServlet(WebApplicationContext)
* @see #setContextClass
* @see #setContextConfigLocation
*/
protected WebApplicationContext initWebApplicationContext() {
//先從ServletContext中獲得父容器WebAppliationContext
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
//聲明子容器
WebApplicationContext wac = null;
//建立父氧秘、子容器之間的關聯(lián)關系
if (this.webApplicationContext != null) {
// A context instance was injected at construction time -> use it
wac = this.webApplicationContext;
if (wac instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
if (!cwac.isActive()) {
// The context has not yet been refreshed -> provide services such as
// setting the parent context, setting the application context id, etc
if (cwac.getParent() == null) {
// The context instance was injected without an explicit parent -> set
// the root application context (if any; may be null) as the parent
cwac.setParent(rootContext);
}
//這個方法里面調用了AbatractApplication的refresh()方法
//模板方法,規(guī)定IOC初始化基本流程
configureAndRefreshWebApplicationContext(cwac);
}
}
}
//先去ServletContext中查找Web容器的引用是否存在趴久,并創(chuàng)建好默認的空IOC容器
if (wac == null) {
// No context instance was injected at construction time -> see if one
// has been registered in the servlet context. If one exists, it is assumed
// that the parent context (if any) has already been set and that the
// user has performed any initialization such as setting the context id
wac = findWebApplicationContext();
}
//給上一步創(chuàng)建好的IOC容器賦值
if (wac == null) {
// No context instance is defined for this servlet -> create a local one
wac = createWebApplicationContext(rootContext);
}
//觸發(fā)onRefresh方法
if (!this.refreshEventReceived) {
// Either the context is not a ConfigurableApplicationContext with refresh
// support or the context injected at construction time had already been
// refreshed -> trigger initial onRefresh manually here.
onRefresh(wac);
}
if (this.publishContext) {
// Publish the context as a servlet context attribute.
String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
"' as ServletContext attribute with name [" + attrName + "]");
}
}
return wac;
}
在上面代碼中我們看到了熟悉的initWebApplicationContext()方法丸相,繼續(xù)跟進:
/**
* Initialize and publish the WebApplicationContext for this servlet.
* <p>Delegates to {@link #createWebApplicationContext} for actual creation
* of the context. Can be overridden in subclasses.
* @return the WebApplicationContext instance
* @see #FrameworkServlet(WebApplicationContext)
* @see #setContextClass
* @see #setContextConfigLocation
*/
protected WebApplicationContext initWebApplicationContext() {
//先從ServletContext中獲得父容器WebAppliationContext
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
//聲明子容器
WebApplicationContext wac = null;
//建立父、子容器之間的關聯(lián)關系
if (this.webApplicationContext != null) {
// A context instance was injected at construction time -> use it
wac = this.webApplicationContext;
if (wac instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
if (!cwac.isActive()) {
// The context has not yet been refreshed -> provide services such as
// setting the parent context, setting the application context id, etc
if (cwac.getParent() == null) {
// The context instance was injected without an explicit parent -> set
// the root application context (if any; may be null) as the parent
cwac.setParent(rootContext);
}
//這個方法里面調用了AbatractApplication的refresh()方法
//模板方法彼棍,規(guī)定IOC初始化基本流程
configureAndRefreshWebApplicationContext(cwac);
}
}
}
//先去ServletContext中查找Web容器的引用是否存在灭忠,并創(chuàng)建好默認的空IOC容器
if (wac == null) {
// No context instance was injected at construction time -> see if one
// has been registered in the servlet context. If one exists, it is assumed
// that the parent context (if any) has already been set and that the
// user has performed any initialization such as setting the context id
wac = findWebApplicationContext();
}
//給上一步創(chuàng)建好的IOC容器賦值
if (wac == null) {
// No context instance is defined for this servlet -> create a local one
wac = createWebApplicationContext(rootContext);
}
//觸發(fā)onRefresh方法
if (!this.refreshEventReceived) {
// Either the context is not a ConfigurableApplicationContext with refresh
// support or the context injected at construction time had already been
// refreshed -> trigger initial onRefresh manually here.
onRefresh(wac);
}
if (this.publishContext) {
// Publish the context as a servlet context attribute.
String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
"' as ServletContext attribute with name [" + attrName + "]");
}
}
return wac;
}
/**
* Retrieve a {@code WebApplicationContext} from the {@code ServletContext}
* attribute with the {@link #setContextAttribute configured name}. The
* {@code WebApplicationContext} must have already been loaded and stored in the
* {@code ServletContext} before this servlet gets initialized (or invoked).
* <p>Subclasses may override this method to provide a different
* {@code WebApplicationContext} retrieval strategy.
* @return the WebApplicationContext for this servlet, or {@code null} if not found
* @see #getContextAttribute()
*/
@Nullable
protected WebApplicationContext findWebApplicationContext() {
String attrName = getContextAttribute();
if (attrName == null) {
return null;
}
WebApplicationContext wac =
WebApplicationContextUtils.getWebApplicationContext(getServletContext(), attrName);
if (wac == null) {
throw new IllegalStateException("No WebApplicationContext found: initializer not registered?");
}
return wac;
}
/**
* Instantiate the WebApplicationContext for this servlet, either a default
* {@link org.springframework.web.context.support.XmlWebApplicationContext}
* or a {@link #setContextClass custom context class}, if set.
* <p>This implementation expects custom contexts to implement the
* {@link org.springframework.web.context.ConfigurableWebApplicationContext}
* interface. Can be overridden in subclasses.
* <p>Do not forget to register this servlet instance as application listener on the
* created context (for triggering its {@link #onRefresh callback}, and to call
* {@link org.springframework.context.ConfigurableApplicationContext#refresh()}
* before returning the context instance.
* @param parent the parent ApplicationContext to use, or {@code null} if none
* @return the WebApplicationContext for this servlet
* @see org.springframework.web.context.support.XmlWebApplicationContext
*/
protected WebApplicationContext createWebApplicationContext(@Nullable ApplicationContext parent) {
Class<?> contextClass = getContextClass();
if (this.logger.isDebugEnabled()) {
this.logger.debug("Servlet with name '" + getServletName() +
"' will try to create custom WebApplicationContext context of class '" +
contextClass.getName() + "'" + ", using parent context [" + parent + "]");
}
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException(
"Fatal initialization error in servlet with name '" + getServletName() +
"': custom WebApplicationContext class [" + contextClass.getName() +
"] is not of type ConfigurableWebApplicationContext");
}
ConfigurableWebApplicationContext wac =
(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
wac.setEnvironment(getEnvironment());
wac.setParent(parent);
String configLocation = getContextConfigLocation();
if (configLocation != null) {
wac.setConfigLocation(configLocation);
}
configureAndRefreshWebApplicationContext(wac);
return wac;
}
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
// The application context id is still set to its original default value
// -> assign a more useful id based on available information
if (this.contextId != null) {
wac.setId(this.contextId);
}
else {
// Generate default id...
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(getServletContext().getContextPath()) + '/' + getServletName());
}
}
wac.setServletContext(getServletContext());
wac.setServletConfig(getServletConfig());
wac.setNamespace(getNamespace());
wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));
// The wac environment's #initPropertySources will be called in any case when the context
// is refreshed; do it eagerly here to ensure servlet property sources are in place for
// use in any post-processing or initialization that occurs below prior to #refresh
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(getServletContext(), getServletConfig());
}
postProcessWebApplicationContext(wac);
applyInitializers(wac);
wac.refresh();
}
??從上面代碼中可以看出configureAndRefreshWebApplicationContext方法中真正調用了refresh()方法,這個是啟動IOC容器的入口座硕。IOC容器初始化之后弛作,最后調用了DispatcherServlet的onRefresh()方法,在onRefresh方法中华匾,又是直接調用initStrategies()方法初始化SpringMvc的九大組件:
/**
* Initialize the strategy objects that this servlet uses.
* <p>May be overridden in subclasses in order to initialize further strategy objects.
*/
//初始化策略
protected void initStrategies(ApplicationContext context) {
//多文件上傳的組件
initMultipartResolver(context);
//初始化本地語言環(huán)境
initLocaleResolver(context);
//初始化模板處理器
initThemeResolver(context);
//handlerMapping
initHandlerMappings(context);
//初始化參數(shù)適配器
initHandlerAdapters(context);
//初始化異常攔截器
initHandlerExceptionResolvers(context);
//初始化視圖預處理器
initRequestToViewNameTranslator(context);
//初始化視圖轉換器
initViewResolvers(context);
//FlashMap管理器
initFlashMapManager(context);
}
基于XML的IOC容器初始化
??IOC容器的初始化包括BeanDefinition的定位映琳、加載、注冊這三個基本流程蜘拉。以ApplicationContext為例子萨西,ApplicationContext系列容器也許是我們最熟悉的容器,因為WEB項目中使用的XmlApplicationContext就屬于這個繼承體系旭旭,還有ClassPathXmlApplicationContext等谎脯,其繼承體系如下:
??ApplicationContext允許上下文嵌套,通過保持父上下文可以維持一個上下文體系持寄。對于Bean的查找可以在這個上下文體系中發(fā)生源梭,首先檢查當前上下文娱俺,其次是父上下文,逐級向上废麻,這樣為不同的Spring 應用提供了一個共享的Bean定義環(huán)境矢否。
1.尋找入口
??ClassPathXmlApplicationContext,通過main()方法啟動:
ApplicationContext app = new ClassPathXmlApplicationContext("application.xml")脑溢;
先看其構造函數(shù)的調用:
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[] {configLocation}, true, null);
}
實際調用:
/**
* Create a new ClassPathXmlApplicationContext with the given parent,
* loading the definitions from the given XML files.
* @param configLocations array of resource locations
* @param refresh whether to automatically refresh the context,
* loading all bean definitions and creating all singletons.
* Alternatively, call refresh manually after further configuring the context.
* @param parent the parent context
* @throws BeansException if context creation failed
* @see #refresh()
*/
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
//重啟、刷新赖欣、重置
refresh();
}
}
??AnnotationConfigApplicationContext屑彻、FileSystemXmlApplicationContext、XmlWebApplicationContext等都繼承自父容器AbstractApplicationContext主要用到了裝飾器模式和策略模式顶吮,最終都調用refresh()方法:
2.獲取配置路徑
??通過分析ClassPathXmlApplictionContext的源代碼可以知道社牲,在創(chuàng)建ClassPathXmlApplicationContext容器時,構造方法做以下兩項重要工作:
第一悴了,調用父類容器的構造方法搏恤,super(parent);
為容器設置好Bean資源的加載器。
第二湃交,調用父類AbstractRefreshableConfigApplicationContext的setConfigLocations(configLocations);
方法熟空,設置Bean配置信息的定位路徑。
這里需要追蹤一下AbstractApplicationContext
/**
* Set the config locations for this application context in init-param style,
* i.e. with distinct locations separated by commas, semicolons or whitespace.
* <p>If not set, the implementation may use a default as appropriate.
*/
//處理單個資源文件路徑為一個字符串的情況
public void setConfigLocation(String location) {
//String CONFIG_LOCATION_DELIMITERS = ",; /t/n";
//即多個資源文件路徑之間用” ,; \t\n”分隔搞莺,解析成數(shù)組形式
setConfigLocations(StringUtils.tokenizeToStringArray(location, CONFIG_LOCATION_DELIMITERS));
}
/**
* Set the config locations for this application context.
* <p>If not set, the implementation may use a default as appropriate.
*/
//解析Bean定義資源文件的路徑息罗,處理多個資源文件字符串數(shù)組
public void setConfigLocations(@Nullable String... locations) {
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++) {
// resolvePath為同一個類中將字符串解析為路徑的方法
this.configLocations[i] = resolvePath(locations[i]).trim();
}
}
else {
this.configLocations = null;
}
}
通過這兩個方法源碼我們可以看出,我們既可以使用一個字符串來配置多個SpringBean的配置信息才沧,也可以使用字符串數(shù)組迈喉。
到這里,SpringIOC容器會將配置Bean配置信息定位為Spring封裝的Resource温圆。
具體可以看看PathMatchingResourcePatternResolver這個類挨摸。
第三,開始啟動岁歉。
??SpringIOC容器對Bean配置資源載入是從refresh();
方法開始的得运,refresh()是一個模板方法,規(guī)定了IOC容器的啟動流程刨裆,有些邏輯要交給其子類去實現(xiàn)澈圈。它對Bean配置的資源進行載入ClassPathXmlApplicationContext通過調用其父類AbstractApplicationContext的refresh();
函數(shù)啟動整個IOC容器對Bean定義載入過程,現(xiàn)在我們來詳細看看refresh();
中的邏輯處理:
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
//1帆啃、調用容器準備刷新的方法瞬女,獲取容器的當時時間,同時給容器設置同步標識
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
//2努潘、告訴子類啟動refreshBeanFactory()方法诽偷,Bean定義資源文件的載入從
//子類的refreshBeanFactory()方法啟動
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
//3坤学、為BeanFactory配置容器特性,例如類加載器报慕、事件處理器等
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
//4深浮、為容器的某些子類指定特殊的BeanPost事件處理器
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
//5、調用所有注冊的BeanFactoryPostProcessor的Bean
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
//6眠冈、為BeanFactory注冊BeanPost事件處理器.
//BeanPostProcessor是Bean后置處理器飞苇,用于監(jiān)聽容器觸發(fā)的事件
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
//7、初始化信息源蜗顽,和國際化相關.
initMessageSource();
// Initialize event multicaster for this context.
//8布卡、初始化容器事件傳播器.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
//9、調用子類的某些特殊Bean初始化方法
onRefresh();
// Check for listener beans and register them.
//10雇盖、為事件傳播器注冊事件監(jiān)聽器.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
//11忿等、初始化所有剩余的單例Bean
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
//12、初始化容器的生命周期事件處理器崔挖,并發(fā)布容器的生命周期事件
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.
//13、銷毀已創(chuàng)建的Bean
destroyBeans();
// Reset 'active' flag.
//14薛匪、取消refresh操作蛋辈,重置容器的同步標識冷溶。
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...
//15尊浓、重設公共緩存
resetCommonCaches();
}
}
}
??refresh()
方法主要為IOC容器Bean的生命周期管理提供條件逞频,SpringIOC容器載入Bean信息,從其子類容器的refreshBeanFactory()方法啟動栋齿,所以整個refresh()
方法從
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
??這句代碼后都是注冊容器的信息源和生命周期事件苗胀,我們前面說的載入就是從這距代碼開始啟動。
??refresh();
方法主要作用是:在創(chuàng)建IOC容器前瓦堵,如果已經有容器存在基协,則需要把已有的容器銷毀和關閉,以保證在refresh之后使用的是新建立起來的IOC容器菇用。它類似于對IOC容器的重啟澜驮,在新建好的容器中,對容器進行初始化惋鸥,對Bean配置資源進行載入杂穷。
4.創(chuàng)建容器
obtainFreshBeanFactory();
方法調用子類容器的refreshBeanFactroy()方法飞蚓,啟動容器載入Bean配置信息的過程:
/**
* Tell the subclass to refresh the internal bean factory.
* @return the fresh BeanFactory instance
* @see #refreshBeanFactory()
* @see #getBeanFactory()
*/
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
//這里使用了委派設計模式八堡,父類定義了抽象的refreshBeanFactory()方法汰现,具體實現(xiàn)調用子類容器的refreshBeanFactory()方法
refreshBeanFactory();
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}
AbstractApplicationContext類中只抽象定義了refreshBeanFactory();
方法,容器真正調用的是其子類AbstractRefreshableApplicationContext實現(xiàn)的方法
/**
* This implementation performs an actual refresh of this context's underlying
* bean factory, shutting down the previous bean factory (if any) and
* initializing a fresh bean factory for the next phase of the context's lifecycle.
*/
@Override
protected final void refreshBeanFactory() throws BeansException {
//如果已經有容器,銷毀容器中的bean,關閉容器
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
//創(chuàng)建IOC容器
DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId());
//對IOC容器進行定制化东且,如設置啟動參數(shù)色查,開啟注解的自動裝配等
customizeBeanFactory(beanFactory);
//調用載入Bean定義的方法,主要這里又使用了一個委派模式好港,在當前類中只定義了抽象的loadBeanDefinitions方法,具體的實現(xiàn)調用子類容器
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
??在這個方法中,先判斷了BeanFactroy是否存在,如果存在則先銷毀beans并關閉beanFactory尊剔,接著創(chuàng)建DefaultListableBeanFactory,并調用了loadBeanDefinitions(beanFactory);
裝在bean定義。
5.載入配置路徑
??AbstractRefreshableApplicationContext中只定義了抽象的
loadBeanDefinitions(beanFactory);
方法祭椰,容器真正調用的是其子類AbstractXmlApplicationContext
/**
* Loads the bean definitions via an XmlBeanDefinitionReader.
* @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader
* @see #initBeanDefinitionReader
* @see #loadBeanDefinitions
*/
//實現(xiàn)父類抽象的載入Bean定義方法
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
//創(chuàng)建XmlBeanDefinitionReader臣淤,即創(chuàng)建Bean讀取器,并通過回調設置到容器中去,容 器使用該讀取器讀取Bean定義資源
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's
// resource loading environment.
//為Bean讀取器設置Spring資源加載器,AbstractXmlApplicationContext的
//祖先父類AbstractApplicationContext繼承DefaultResourceLoader览绿,因此逛绵,容器本身也是一個資源加載器
beanDefinitionReader.setEnvironment(this.getEnvironment());
beanDefinitionReader.setResourceLoader(this);
//為Bean讀取器設置SAX xml解析器
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
//當Bean讀取器讀取Bean定義的Xml資源文件時,啟用Xml的校驗機制
initBeanDefinitionReader(beanDefinitionReader);
//Bean讀取器真正實現(xiàn)加載的方法
loadBeanDefinitions(beanDefinitionReader);
}
/**
* Load the bean definitions with the given XmlBeanDefinitionReader.
* <p>The lifecycle of the bean factory is handled by the {@link #refreshBeanFactory}
* method; hence this method is just supposed to load and/or register bean definitions.
* @param reader the XmlBeanDefinitionReader to use
* @throws BeansException in case of bean registration errors
* @throws IOException if the required XML document isn't found
* @see #refreshBeanFactory
* @see #getConfigLocations
* @see #getResources
* @see #getResourcePatternResolver
*/
//Xml Bean讀取器加載Bean定義資源
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
//獲取Bean定義資源的定位
Resource[] configResources = getConfigResources();
if (configResources != null) {
//Xml Bean讀取器調用其父類AbstractBeanDefinitionReader讀取定位
//的Bean定義資源
reader.loadBeanDefinitions(configResources);
}
//如果子類中獲取的Bean定義資源定位為空,則獲取FileSystemXmlApplicationContext構造方法中setConfigLocations方法設置的資源
String[] configLocations = getConfigLocations();
if (configLocations != null) {
//Xml Bean讀取器調用其父類AbstractBeanDefinitionReader讀取定位
//的Bean定義資源
reader.loadBeanDefinitions(configLocations);
}
}
/**
* Return an array of Resource objects, referring to the XML bean definition
* files that this context should be built with.
* <p>The default implementation returns {@code null}. Subclasses can override
* this to provide pre-built Resource objects rather than location Strings.
* @return an array of Resource objects, or {@code null} if none
* @see #getConfigLocations()
*/
//這里又使用了一個委托模式,調用子類的獲取Bean定義資源定位的方法
//該方法在ClassPathXmlApplicationContext中進行實現(xiàn)普监,對于我們
//舉例分析源碼的FileSystemXmlApplicationContext沒有使用該方法
@Nullable
protected Resource[] getConfigResources() {
return null;
}
??以XmlBean讀取器的其中一種策略XmlBeanDefinitionReader為例子。XmlBeanDefinitionReader調用其父類AbstractBeanDefinitionReader的reader.loadBeanDefinition()
方法讀取Bean配置資源。由于我們使用ClassPathXmlApplicationContext作為例子分析,因此getConfigResources返回值為null缭受,因此程序執(zhí)行reader.loadBeanDefinitions(configLocations);
分支蔓搞。
6.分配路徑處理策略
??在XmlBeanDefinitionReader的抽象父類AbstractBeanDefinitionReader定義了載入過程。
具體源碼如下:
//重載方法酸员,調用下面的loadBeanDefinitions(String, Set<Resource>);方法
@Override
public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
return loadBeanDefinitions(location, null);
}
/**
* Load bean definitions from the specified resource location.
* <p>The location can also be a location pattern, provided that the
* ResourceLoader of this bean definition reader is a ResourcePatternResolver.
* @param location the resource location, to be loaded with the ResourceLoader
* (or ResourcePatternResolver) of this bean definition reader
* @param actualResources a Set to be filled with the actual Resource objects
* that have been resolved during the loading process. May be {@code null}
* to indicate that the caller is not interested in those Resource objects.
* @return the number of bean definitions found
* @throws BeanDefinitionStoreException in case of loading or parsing errors
* @see #getResourceLoader()
* @see #loadBeanDefinitions(org.springframework.core.io.Resource)
* @see #loadBeanDefinitions(org.springframework.core.io.Resource[])
*/
public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
//獲取在IoC容器初始化過程中設置的資源加載器
ResourceLoader resourceLoader = getResourceLoader();
if (resourceLoader == null) {
throw new BeanDefinitionStoreException(
"Cannot import bean definitions from location [" + location + "]: no ResourceLoader available");
}
if (resourceLoader instanceof ResourcePatternResolver) {
// Resource pattern matching available.
try {
//將指定位置的Bean定義資源文件解析為Spring IOC容器封裝的資源
//加載多個指定位置的Bean定義資源文件
Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
//委派調用其子類XmlBeanDefinitionReader的方法,實現(xiàn)加載功能
int loadCount = loadBeanDefinitions(resources);
if (actualResources != null) {
for (Resource resource : resources) {
actualResources.add(resource);
}
}
if (logger.isDebugEnabled()) {
logger.debug("Loaded " + loadCount + " bean definitions from location pattern [" + location + "]");
}
return loadCount;
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(
"Could not resolve bean definition resource pattern [" + location + "]", ex);
}
}
else {
// Can only load single resources by absolute URL.
//將指定位置的Bean定義資源文件解析為Spring IOC容器封裝的資源
//加載單個指定位置的Bean定義資源文件
Resource resource = resourceLoader.getResource(location);
//委派調用其子類XmlBeanDefinitionReader的方法,實現(xiàn)加載功能
int loadCount = loadBeanDefinitions(resource);
if (actualResources != null) {
actualResources.add(resource);
}
if (logger.isDebugEnabled()) {
logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]");
}
return loadCount;
}
}
//重載方法,調用loadBeanDefinitions(String);
@Override
public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
Assert.notNull(locations, "Location array must not be null");
int counter = 0;
for (String location : locations) {
counter += loadBeanDefinitions(location);
}
return counter;
}
??AbstractRefreshableConfigApplictionContext的loadBeanDefintion(Resource .. resources)
方法實際上調用了AbstractBeanDefinitionReader的loadBeanDefintion()
方法。從對AbstractBeanDefinitionRead的loadBeanDefintion()
方法源碼分析得出結論:
?調用資源加載器的獲取資源方法esourceLoader.getResource(location);
匠璧,獲取到要加載的資源媳维。
真正執(zhí)行加載功能是其子類XmlBeanDefinitionReader的loadBeanDefintion()
方法。跟進去發(fā)現(xiàn)getResources()
方法其實定義在ResourcePatternResolver中。
ResourcePatternResolver類圖:
?&emsp從上面可以看到ResourceLoader與ApplicationContext的繼承關系盖灸,可以看出其實際調用是DefaultResourceLoader中的getSource()
方法定位Resource钾腺,因為ClassPathXmlApplicaitonContext本身就是DefaultResourceLoader的實現(xiàn)類,所以此時又回到ClassPathXmlApplicationContext中來了。
7.配置解析文件路徑
??XmlBeanDefinitionReader通過調用ClassPathXmlApplicationContext的父類DefaultResourceLoader的getResource();
方法獲取資源,其源碼如下:
//獲取Resource的具體實現(xiàn)方法
@Override
public Resource getResource(String location) {
Assert.notNull(location, "Location must not be null");
for (ProtocolResolver protocolResolver : this.protocolResolvers) {
Resource resource = protocolResolver.resolve(location, this);
if (resource != null) {
return resource;
}
}
//如果是類路徑的方式笆焰,那需要使用ClassPathResource 來得到bean 文件的資源對象
if (location.startsWith("/")) {
return getResourceByPath(location);
}
else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
}
else {
try {
// Try to parse the location as a URL...
// 如果是URL 方式叠国,使用UrlResource 作為bean 文件的資源對象
URL url = new URL(location);
return (ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));
}
catch (MalformedURLException ex) {
// No URL -> resolve as resource path.
//如果既不是classpath標識孙蒙,又不是URL標識的Resource定位,則調用
//容器本身的getResourceByPath方法獲取Resource
return getResourceByPath(location);
}
}
}
??** DefaultResourceLoader**提供了getResourceByPath()
方法實現(xiàn),就是為了處理既不是classpath標識峭咒,又不是URL的Resource定位的這種情況幔翰。
protected Resource getResourceByPath(String path) {
return new ClassPathContextResource(path, getClassLoader());
}
??在ClassPathResource中完成了對整個路徑的解析。這樣赋访,我們就可以從類路徑上對IOC配置文件進行加載步悠,當然我們可以按照這個邏輯從任何地方加載,在Spring中我們看到它提供的各種資源抽象谚咬,比如ClassPathResource秉继、URLResource、FileStystemResource等來供我們使用月褥。上面我們看到的是定位Resource的過程灯荧,這只是加載過程的一部分哆窿。例如FileSystemXmlApplication容器就重寫了getResourceByPath();
方法:
@Override
protected Resource getResourceByPath(String path) {
if (path.startsWith("/")) {
path = path.substring(1);
}
//這里使用文件系統(tǒng)資源對象來定義bean 文件
return new FileSystemResource(path);
}
通過子類覆蓋,巧妙完成了講類路徑變?yōu)槲募窂健?/p>
8.開始讀取配置內容
??繼續(xù)回到XmlBeanDefinitionReader的loadBeanDefinitions(Resource ... resources)
方法看到代表bean文件的資源定義以后的加載過程焕妙。
//XmlBeanDefinitionReader加載資源的入口方法
@Override
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
//將讀入的XML資源進行特殊編碼處理
return loadBeanDefinitions(new EncodedResource(resource));
}
//這里是載入XML形式Bean定義資源文件方法
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<>(4);
this.resourcesCurrentlyBeingLoaded.set(currentResources);
}
if (!currentResources.add(encodedResource)) {
throw new BeanDefinitionStoreException(
"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
}
try {
//將資源文件轉為InputStream的IO流
InputStream inputStream = encodedResource.getResource().getInputStream();
try {
//從InputStream中得到XML的解析源
InputSource inputSource = new InputSource(inputStream);
if (encodedResource.getEncoding() != null) {
inputSource.setEncoding(encodedResource.getEncoding());
}
//這里是具體的讀取過程
return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
}
finally {
//關閉從Resource中得到的IO流
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();
}
}
}
//從特定XML文件中實際載入Bean定義資源的方法
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
//將XML文件轉換為DOM對象置谦,解析過程由documentLoader實現(xiàn)
Document doc = doLoadDocument(inputSource, resource);
//這里是啟動對Bean定義解析的詳細過程,該解析過程會用到Spring的Bean配置規(guī)則
return registerBeanDefinitions(doc, resource);
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (SAXParseException ex) {
throw new XmlBeanDefinitionStoreException(resource.getDescription(),
"Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex);
}
catch (SAXException ex) {
throw new XmlBeanDefinitionStoreException(resource.getDescription(),
"XML document from " + resource + " is invalid", ex);
}
catch (ParserConfigurationException ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"Parser configuration exception parsing XML from " + resource, ex);
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"IOException parsing XML document from " + resource, ex);
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"Unexpected exception parsing XML document from " + resource, ex);
}
}
??通過源碼分析,載入Bean配置信息的最后一步是講Bean配置信息轉換為Document對象敏晤,該過程由doLoadDocument(inputSource, resource);
方法實現(xiàn)男摧。
9.準備文檔對象
??DocumentLoader將Bean配置的資源轉化為Document
對象源碼如下:
//使用標準的JAXP將載入的Bean定義資源轉換成document對象
@Override
public Document loadDocument(InputSource inputSource, EntityResolver entityResolver,
ErrorHandler errorHandler, int validationMode, boolean namespaceAware) throws Exception {
//創(chuàng)建文件解析器工廠
DocumentBuilderFactory factory = createDocumentBuilderFactory(validationMode, namespaceAware);
if (logger.isDebugEnabled()) {
logger.debug("Using JAXP provider [" + factory.getClass().getName() + "]");
}
//創(chuàng)建文檔解析器
DocumentBuilder builder = createDocumentBuilder(factory, entityResolver, errorHandler);
//解析Spring的Bean定義資源
return builder.parse(inputSource);
}
protected DocumentBuilderFactory createDocumentBuilderFactory(int validationMode, boolean namespaceAware)
throws ParserConfigurationException {
//創(chuàng)建文檔解析工廠
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(namespaceAware);
//設置解析XML的校驗
if (validationMode != XmlValidationModeDetector.VALIDATION_NONE) {
factory.setValidating(true);
if (validationMode == XmlValidationModeDetector.VALIDATION_XSD) {
// Enforce namespace aware for XSD...
factory.setNamespaceAware(true);
try {
factory.setAttribute(SCHEMA_LANGUAGE_ATTRIBUTE, XSD_SCHEMA_LANGUAGE);
}
catch (IllegalArgumentException ex) {
ParserConfigurationException pcex = new ParserConfigurationException(
"Unable to validate using XSD: Your JAXP provider [" + factory +
"] does not support XML Schema. Are you running on Java 1.4 with Apache Crimson? " +
"Upgrade to Apache Xerces (or Java 1.5) for full XSD support.");
pcex.initCause(ex);
throw pcex;
}
}
}
return factory;
}
protected DocumentBuilder createDocumentBuilder(DocumentBuilderFactory factory,
@Nullable EntityResolver entityResolver, @Nullable ErrorHandler errorHandler)
throws ParserConfigurationException {
DocumentBuilder docBuilder = factory.newDocumentBuilder();
if (entityResolver != null) {
docBuilder.setEntityResolver(entityResolver);
}
if (errorHandler != null) {
docBuilder.setErrorHandler(errorHandler);
}
return docBuilder;
}
??上面的解析過程是調用JavaEE標準的JAXP標準進行處理樟插。SpringIOC容器根據(jù)定位的Bean配置信息鸵熟,將其加載讀入并轉換為Document對象完成。
10.分配解析策略
??XmlBeanDefinitionReader類中的doLoadBeanDefinition()方法是從特定XML文件中實際載入Bean配置資源的方法,該方法在載入Bean配置資源之后將其轉換為Document對象,接下來調用registerBeanDefinitions(Document doc, Resource resource);
啟動SpringIOC容器對Bean定義的解析過程,
//按照Spring的Bean語義要求將Bean定義資源解析并轉換為容器內部數(shù)據(jù)結構
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
//得到BeanDefinitionDocumentReader來對xml格式的BeanDefinition解析
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
//獲得容器中注冊的Bean數(shù)量
int countBefore = getRegistry().getBeanDefinitionCount();
//解析過程入口充易,這里使用了委派模式瑞妇,BeanDefinitionDocumentReader只是個接口,
//具體的解析實現(xiàn)過程有實現(xiàn)類DefaultBeanDefinitionDocumentReader完成
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
//統(tǒng)計解析的Bean數(shù)量
return getRegistry().getBeanDefinitionCount() - countBefore;
}
??Bean配置資源的載入解析分為以下兩個過程:
1.通過調用XML解析器將Bean配置信息轉換得到Document對象。這一步沒有按照Spring的Bean規(guī)則進行解析盐捷。這一步是載入過程滞诺。
2.完成XML通用解析后秦爆,按照Sping定義規(guī)則對Document對象進行解析,其解析過程是在接口BeanDefinitionDocumentReader的實現(xiàn)類中實現(xiàn)的。
11.配置載入內存
??BeanDefinitionDocumentReader接口通過registerBeanDefinition()
方法調用其實現(xiàn)類DefaultBeanDefinitionDocumentReader對Document對象進行解析:
//根據(jù)Spring DTD對Bean的定義規(guī)則解析Bean定義Document對象
@Override
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
//獲得XML描述符
this.readerContext = readerContext;
logger.debug("Loading bean definitions");
//獲得Document的根元素
Element root = doc.getDocumentElement();
doRegisterBeanDefinitions(root);
}
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實現(xiàn)厨剪,
//BeanDefinitionParserDelegate中定義了Spring Bean定義XML文件的各種元素
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)) {
if (logger.isInfoEnabled()) {
logger.info("Skipped XML bean definition file due to specified profiles [" + profileSpec +
"] not matching: " + getReaderContext().getResource());
}
return;
}
}
}
//在解析Bean定義之前,進行自定義的解析直晨,增強解析過程的可擴展性
preProcessXml(root);
//從Document的根元素開始進行Bean定義的Document對象
parseBeanDefinitions(root, this.delegate);
//在解析Bean定義之后搀军,進行自定義的解析,增加解析過程的可擴展性
postProcessXml(root);
this.delegate = parent;
}
//創(chuàng)建BeanDefinitionParserDelegate勇皇,用于完成真正的解析過程
protected BeanDefinitionParserDelegate createDelegate(
XmlReaderContext readerContext, Element root, @Nullable BeanDefinitionParserDelegate parentDelegate) {
BeanDefinitionParserDelegate delegate = new BeanDefinitionParserDelegate(readerContext);
//BeanDefinitionParserDelegate初始化Document根元素
delegate.initDefaults(root, parentDelegate);
return delegate;
}
//使用Spring的Bean規(guī)則從Document的根元素開始進行Bean定義的Document對象
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
//Bean定義的Document對象使用了Spring默認的XML命名空間
if (delegate.isDefaultNamespace(root)) {
//獲取Bean定義的Document對象根元素的所有子節(jié)點
NodeList nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
//獲得Document節(jié)點是XML元素節(jié)點
if (node instanceof Element) {
Element ele = (Element) node;
//Bean定義的Document的元素節(jié)點使用的是Spring默認的XML命名空間
if (delegate.isDefaultNamespace(ele)) {
//使用Spring的Bean規(guī)則解析元素節(jié)點
parseDefaultElement(ele, delegate);
}
else {
//沒有使用Spring默認的XML命名空間,則使用用戶自定義的解//析規(guī)則解析元素節(jié)點
delegate.parseCustomElement(ele);
}
}
}
}
else {
//Document的根節(jié)點沒有使用Spring默認的命名空間诅福,則使用用戶自定義的
//解析規(guī)則解析Document根節(jié)點
delegate.parseCustomElement(root);
}
}
//使用Spring的Bean規(guī)則解析Document元素節(jié)點
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
//如果元素節(jié)點是<Import>導入元素,進行導入解析
if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
importBeanDefinitionResource(ele);
}
//如果元素節(jié)點是<Alias>別名元素乳幸,進行別名解析
else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
processAliasRegistration(ele);
}
//元素節(jié)點既不是導入元素养筒,也不是別名元素盆顾,即普通的<Bean>元素,
//按照Spring的Bean規(guī)則解析元素
else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
processBeanDefinition(ele, delegate);
}
else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
// recurse
doRegisterBeanDefinitions(ele);
}
}
//解析<Import>導入元素浴捆,從給定的導入路徑加載Bean定義資源到Spring IoC容器中
protected void importBeanDefinitionResource(Element ele) {
//獲取給定的導入元素的location屬性
String location = ele.getAttribute(RESOURCE_ATTRIBUTE);
//如果導入元素的location屬性值為空述吸,則沒有導入任何資源璃赡,直接返回
if (!StringUtils.hasText(location)) {
getReaderContext().error("Resource location must not be empty", ele);
return;
}
// Resolve system properties: e.g. "${user.dir}"
//使用系統(tǒng)變量值解析location屬性值
location = getReaderContext().getEnvironment().resolveRequiredPlaceholders(location);
Set<Resource> actualResources = new LinkedHashSet<>(4);
// Discover whether the location is an absolute or relative URI
//標識給定的導入元素的location是否是絕對路徑
boolean absoluteLocation = false;
try {
absoluteLocation = ResourcePatternUtils.isUrl(location) || ResourceUtils.toURI(location).isAbsolute();
}
catch (URISyntaxException ex) {
// cannot convert to an URI, considering the location relative
// unless it is the well-known Spring prefix "classpath*:"
//給定的導入元素的location不是絕對路徑
}
// Absolute or relative?
//給定的導入元素的location是絕對路徑
if (absoluteLocation) {
try {
//使用資源讀入器加載給定路徑的Bean定義資源
int importCount = getReaderContext().getReader().loadBeanDefinitions(location, actualResources);
if (logger.isDebugEnabled()) {
logger.debug("Imported " + importCount + " bean definitions from URL location [" + location + "]");
}
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error(
"Failed to import bean definitions from URL location [" + location + "]", ele, ex);
}
}
else {
// No URL -> considering resource location as relative to the current file.
//給定的導入元素的location是相對路徑
try {
int importCount;
//將給定導入元素的location封裝為相對路徑資源
Resource relativeResource = getReaderContext().getResource().createRelative(location);
//封裝的相對路徑資源存在
if (relativeResource.exists()) {
//使用資源讀入器加載Bean定義資源
importCount = getReaderContext().getReader().loadBeanDefinitions(relativeResource);
actualResources.add(relativeResource);
}
//封裝的相對路徑資源不存在
else {
//獲取Spring IOC容器資源讀入器的基本路徑
String baseLocation = getReaderContext().getResource().getURL().toString();
//根據(jù)Spring IOC容器資源讀入器的基本路徑加載給定導入路徑的資源
importCount = getReaderContext().getReader().loadBeanDefinitions(
StringUtils.applyRelativePath(baseLocation, location), actualResources);
}
if (logger.isDebugEnabled()) {
logger.debug("Imported " + importCount + " bean definitions from relative location [" + location + "]");
}
}
catch (IOException ex) {
getReaderContext().error("Failed to resolve current resource location", ele, ex);
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error("Failed to import bean definitions from relative location [" + location + "]",
ele, ex);
}
}
Resource[] actResArray = actualResources.toArray(new Resource[actualResources.size()]);
//在解析完<Import>元素之后纺棺,發(fā)送容器導入其他資源處理完成事件
getReaderContext().fireImportProcessed(location, actResArray, extractSource(ele));
}
??通過上述Spring IOC容器對載入的Bean定義Document解析可以看出,Spring配置文件可以使用<import>元素來導入IOC容器所需要的其他資源,Spring IOC容器在解析時會將指定導入的資源加載到容器中故源。使用<aliase>別名時秆麸,Spring IOC容器首先將別名元素所定義的別名注冊到容器去凌蔬。
??對于既不是<import>元素褐桌,又不是<aliase>元素的元素,即Spring配置文件中普通的<bean>元素的解析由BeanDefinitionParserDelegate類的
parseBeanDefinitionElement()
方法來實現(xiàn)采盒。這個解析過程非常復雜踱侣。
12.載入<bean>元素
??Bean配置信息中的<import>和<alias>元素解析在DefaultBeanDefinitionDocumentReader中已經完成,對Bean配置信息中使用最多的<bean>元素交由BeanDefinitionParserDelegate來解析:
//解析<Bean>元素的入口
@Nullable
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele) {
return parseBeanDefinitionElement(ele, null);
}
//解析Bean定義資源文件中的<Bean>元素,這個方法中主要處理<Bean>元素的id,name和別名屬性
@Nullable
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean) {
//獲取<Bean>元素中的id屬性值
String id = ele.getAttribute(ID_ATTRIBUTE);
//獲取<Bean>元素中的name屬性值
String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
//獲取<Bean>元素中的alias屬性值
List<String> aliases = new ArrayList<>();
//將<Bean>元素中的所有name屬性值存放到別名中
if (StringUtils.hasLength(nameAttr)) {
String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
aliases.addAll(Arrays.asList(nameArr));
}
String beanName = id;
//如果<Bean>元素中沒有配置id屬性時僧家,將別名中的第一個值賦值給beanName
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");
}
}
//檢查<Bean>元素所配置的id或者name的唯一性,containingBean標識<Bean>
//元素中是否包含子<Bean>元素
if (containingBean == null) {
//檢查<Bean>元素所配置的id、name或者別名是否重復
checkNameUniqueness(beanName, aliases, ele);
}
//詳細對<Bean>元素中配置的Bean定義進行解析的地方
AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
if (beanDefinition != null) {
if (!StringUtils.hasText(beanName)) {
try {
if (containingBean != null) {
//如果<Bean>元素中沒有配置id左敌、別名或者name豆胸,且沒有包含子元素
//<Bean>元素,為解析的Bean生成一個唯一beanName并注冊
beanName = BeanDefinitionReaderUtils.generateBeanName(
beanDefinition, this.readerContext.getRegistry(), true);
}
else {
//如果<Bean>元素中沒有配置id、別名或者name猿规,且包含了子元素
//<Bean>元素,為解析的Bean使用別名向IOC容器注冊
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.
//為解析的Bean使用別名注冊時渴庆,為了向后兼容
//Spring1.2/2.0铃芦,給別名添加類名后綴
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);
}
//當解析出錯時,返回null
return null;
}
//詳細對<Bean>元素中配置的Bean定義其他屬性進行解析
//由于上面的方法中已經對Bean的id襟雷、name和別名等屬性進行了處理
//該方法中主要處理除這三個以外的其他屬性數(shù)據(jù)
@Nullable
public AbstractBeanDefinition parseBeanDefinitionElement(
Element ele, String beanName, @Nullable BeanDefinition containingBean) {
//記錄解析的<Bean>
this.parseState.push(new BeanEntry(beanName));
//這里只讀取<Bean>元素中配置的class名字刃滓,然后載入到BeanDefinition中去
//只是記錄配置的class名字,不做實例化耸弄,對象的實例化在依賴注入時完成
String className = null;
//如果<Bean>元素中配置了parent屬性咧虎,則獲取parent屬性的值
if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
}
String parent = null;
if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
parent = ele.getAttribute(PARENT_ATTRIBUTE);
}
try {
//根據(jù)<Bean>元素配置的class名稱和parent屬性值創(chuàng)建BeanDefinition
//為載入Bean定義信息做準備
AbstractBeanDefinition bd = createBeanDefinition(className, parent);
//對當前的<Bean>元素中配置的一些屬性進行解析和設置,如配置的單態(tài)(singleton)屬性等
parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
//為<Bean>元素解析的Bean設置description信息
bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
//對<Bean>元素的meta(元信息)屬性解析
parseMetaElements(ele, bd);
//對<Bean>元素的lookup-method屬性解析
parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
//對<Bean>元素的replaced-method屬性解析
parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
//解析<Bean>元素的構造方法設置
parseConstructorArgElements(ele, bd);
//解析<Bean>元素的<property>設置
parsePropertyElements(ele, bd);
//解析<Bean>元素的qualifier屬性
parseQualifierElements(ele, bd);
//為當前解析的Bean設置所需的資源和依賴對象
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();
}
//解析<Bean>元素出錯時计呈,返回null
return null;
}
??對Spring配置文件比較熟悉的人砰诵,通過上述代碼的分析,就會明白我們在Spring配置文件中<Bean>元素的中配置的屬性就是通過該方法解析和設置到Bean中捌显。
注:在解析<Bean>元素過程中茁彭,并沒有創(chuàng)建和實例化對象。只是創(chuàng)建了Bean對象的定義類BeanDefinition扶歪,將<Bean>元素中的配置信息設置到BeanDefinition中作為記錄理肺,當依賴注入時候才使用這些記錄創(chuàng)建和實例化具體Bean對象。
??上面方法中配置元數(shù)據(jù)(meta)善镰、qualifier等的解析妹萨,在Spring中配置時使用不多,我們在使用Spring的<Bean>元素時媳禁,配置最多的就是<property>眠副。
13.載入<property>元素
??BeanDefinitionParserDelegate在解析<Bean>調用parsePropertyElement()
方法解析<Bean>元素中<property>屬性子元素,源碼如下:
//解析<property>元素
public void parsePropertyElement(Element ele, BeanDefinition bd) {
//獲取<property>元素的名字
String propertyName = ele.getAttribute(NAME_ATTRIBUTE);
if (!StringUtils.hasLength(propertyName)) {
error("Tag 'property' must have a 'name' attribute", ele);
return;
}
this.parseState.push(new PropertyEntry(propertyName));
try {
//如果一個Bean中已經有同名的property存在竣稽,則不進行解析,直接返回霍弹。
//即如果在同一個Bean中配置同名的property毫别,則只有第一個起作用
if (bd.getPropertyValues().contains(propertyName)) {
error("Multiple 'property' definitions for property '" + propertyName + "'", ele);
return;
}
//解析獲取property的值
Object val = parsePropertyValue(ele, bd, propertyName);
//根據(jù)property的名字和值創(chuàng)建property實例
PropertyValue pv = new PropertyValue(propertyName, val);
//解析<property>元素中的屬性
parseMetaElements(ele, pv);
pv.setSource(extractSource(ele));
bd.getPropertyValues().addPropertyValue(pv);
}
finally {
this.parseState.pop();
}
}
//解析獲取property值
@Nullable
public Object parsePropertyValue(Element ele, BeanDefinition bd, @Nullable String propertyName) {
String elementName = (propertyName != null) ?
"<property> element for property '" + propertyName + "'" :
"<constructor-arg> element";
// Should only have one child element: ref, value, list, etc.
//獲取<property>的所有子元素,只能是其中一種類型:ref,value,list,etc等
NodeList nl = ele.getChildNodes();
Element subElement = null;
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
//子元素不是description和meta屬性
if (node instanceof Element && !nodeNameEquals(node, DESCRIPTION_ELEMENT) &&
!nodeNameEquals(node, META_ELEMENT)) {
// Child element is what we're looking for.
if (subElement != null) {
error(elementName + " must not contain more than one sub-element", ele);
}
else {
//當前<property>元素包含有子元素
subElement = (Element) node;
}
}
}
//判斷property的屬性值是ref還是value典格,不允許既是ref又是value
boolean hasRefAttribute = ele.hasAttribute(REF_ATTRIBUTE);
boolean hasValueAttribute = ele.hasAttribute(VALUE_ATTRIBUTE);
if ((hasRefAttribute && hasValueAttribute) ||
((hasRefAttribute || hasValueAttribute) && subElement != null)) {
error(elementName +
" is only allowed to contain either 'ref' attribute OR 'value' attribute OR sub-element", ele);
}
//如果屬性是ref岛宦,創(chuàng)建一個ref的數(shù)據(jù)對象RuntimeBeanReference
//這個對象封裝了ref信息
if (hasRefAttribute) {
String refName = ele.getAttribute(REF_ATTRIBUTE);
if (!StringUtils.hasText(refName)) {
error(elementName + " contains empty 'ref' attribute", ele);
}
//一個指向運行時所依賴對象的引用
RuntimeBeanReference ref = new RuntimeBeanReference(refName);
//設置這個ref的數(shù)據(jù)對象是被當前的property對象所引用
ref.setSource(extractSource(ele));
return ref;
}
//如果屬性是value,創(chuàng)建一個value的數(shù)據(jù)對象TypedStringValue
//這個對象封裝了value信息
else if (hasValueAttribute) {
//一個持有String類型值的對象
TypedStringValue valueHolder = new TypedStringValue(ele.getAttribute(VALUE_ATTRIBUTE));
//設置這個value數(shù)據(jù)對象是被當前的property對象所引用
valueHolder.setSource(extractSource(ele));
return valueHolder;
}
//如果當前<property>元素還有子元素
else if (subElement != null) {
//解析<property>的子元素
return parsePropertySubElement(subElement, bd);
}
else {
// Neither child element nor "ref" or "value" attribute found.
//propery屬性中既不是ref耍缴,也不是value屬性砾肺,解析出錯返回null
error(elementName + " must specify a ref or value", ele);
return null;
}
}
??通過上面的代碼挽霉,我們可以了解在Spring配置文件中,<Bean>元素中<property>元素的相關配置是如何處理的:
1.ref被封裝為指向依賴對象一個引用变汪。
2.value配置都會被封裝為一個字符串對象侠坎。
3.ref和value都通過"解析的數(shù)據(jù)類型屬性值.setSource(extractSource(ele));
方法將屬性值/與引用的屬性關聯(lián)起來。
在方法的最后對于<property>元素的子元素通過parsePropertySubElement(subElement, bd);
方法解析
14.載入<property>子元素
??BeanDefinitionParserDelegate類中parsePropertySubElement(subElement, bd);
方法對<property>中的子元素解析裙盾,源碼如下:
//解析<property>元素中ref,value或者集合等子元素
@Nullable
public Object parsePropertySubElement(Element ele, @Nullable BeanDefinition bd, @Nullable String defaultValueType) {
//如果<property>沒有使用Spring默認的命名空間实胸,則使用用戶自定義的規(guī)則解析內嵌元素
if (!isDefaultNamespace(ele)) {
return parseNestedCustomElement(ele, bd);
}
//如果子元素是bean,則使用解析<Bean>元素的方法解析
else if (nodeNameEquals(ele, BEAN_ELEMENT)) {
BeanDefinitionHolder nestedBd = parseBeanDefinitionElement(ele, bd);
if (nestedBd != null) {
nestedBd = decorateBeanDefinitionIfRequired(ele, nestedBd, bd);
}
return nestedBd;
}
//如果子元素是ref番官,ref中只能有以下3個屬性:bean庐完、local、parent
else if (nodeNameEquals(ele, REF_ELEMENT)) {
// A generic reference to any name of any bean.
//可以不再同一個Spring配置文件中徘熔,具體請參考Spring對ref的配置規(guī)則
String refName = ele.getAttribute(BEAN_REF_ATTRIBUTE);
boolean toParent = false;
if (!StringUtils.hasLength(refName)) {
// A reference to the id of another bean in a parent context.
//獲取<property>元素中parent屬性值门躯,引用父級容器中的Bean
refName = ele.getAttribute(PARENT_REF_ATTRIBUTE);
toParent = true;
if (!StringUtils.hasLength(refName)) {
error("'bean' or 'parent' is required for <ref> element", ele);
return null;
}
}
if (!StringUtils.hasText(refName)) {
error("<ref> element contains empty target attribute", ele);
return null;
}
//創(chuàng)建ref類型數(shù)據(jù),指向被引用的對象
RuntimeBeanReference ref = new RuntimeBeanReference(refName, toParent);
//設置引用類型值是被當前子元素所引用
ref.setSource(extractSource(ele));
return ref;
}
//如果子元素是<idref>酷师,使用解析ref元素的方法解析
else if (nodeNameEquals(ele, IDREF_ELEMENT)) {
return parseIdRefElement(ele);
}
//如果子元素是<value>生音,使用解析value元素的方法解析
else if (nodeNameEquals(ele, VALUE_ELEMENT)) {
return parseValueElement(ele, defaultValueType);
}
//如果子元素是null,為<property>設置一個封裝null值的字符串數(shù)據(jù)
else if (nodeNameEquals(ele, NULL_ELEMENT)) {
// It's a distinguished null value. Let's wrap it in a TypedStringValue
// object in order to preserve the source location.
TypedStringValue nullHolder = new TypedStringValue(null);
nullHolder.setSource(extractSource(ele));
return nullHolder;
}
//如果子元素是<array>窒升,使用解析array集合子元素的方法解析
else if (nodeNameEquals(ele, ARRAY_ELEMENT)) {
return parseArrayElement(ele, bd);
}
//如果子元素是<list>缀遍,使用解析list集合子元素的方法解析
else if (nodeNameEquals(ele, LIST_ELEMENT)) {
return parseListElement(ele, bd);
}
//如果子元素是<set>,使用解析set集合子元素的方法解析
else if (nodeNameEquals(ele, SET_ELEMENT)) {
return parseSetElement(ele, bd);
}
//如果子元素是<map>饱须,使用解析map集合子元素的方法解析
else if (nodeNameEquals(ele, MAP_ELEMENT)) {
return parseMapElement(ele, bd);
}
//如果子元素是<props>域醇,使用解析props集合子元素的方法解析
else if (nodeNameEquals(ele, PROPS_ELEMENT)) {
return parsePropsElement(ele);
}
//既不是ref,又不是value蓉媳,也不是集合譬挚,則子元素配置錯誤,返回null
else {
error("Unknown property sub-element: [" + ele.getNodeName() + "]", ele);
return null;
}
}
??通過上面的代碼酪呻,可以看出Spring配置文件中减宣,對<property>元素中配置的array、list玩荠、set漆腌、map、prop等各種集合子元素的都通過上面的方法解析阶冈,生成對應的數(shù)據(jù)對象闷尿,比如:ManagedList、ManagedArray女坑、ManagedSet等填具,這些Managed類是Spring對象BeanDefinition的數(shù)據(jù)封裝,對集合數(shù)據(jù)類型的具體解析有各自的解析方法實現(xiàn)匆骗。
15.載入<list>的子元素
??BeanDefinitionParserDelegate類中有parseListElement()
方法就是具體解析<property>元素的<list>集合子元素劳景,源碼如下:
//解析<list>集合子元素
public List<Object> parseListElement(Element collectionEle, @Nullable BeanDefinition bd) {
//獲取<list>元素中的value-type屬性誉简,即獲取集合元素的數(shù)據(jù)類型
String defaultElementType = collectionEle.getAttribute(VALUE_TYPE_ATTRIBUTE);
//獲取<list>集合元素中的所有子節(jié)點
NodeList nl = collectionEle.getChildNodes();
//Spring中將List封裝為ManagedList
ManagedList<Object> target = new ManagedList<>(nl.getLength());
target.setSource(extractSource(collectionEle));
//設置集合目標數(shù)據(jù)類型
target.setElementTypeName(defaultElementType);
target.setMergeEnabled(parseMergeAttribute(collectionEle));
//具體的<list>元素解析
parseCollectionElements(nl, target, bd, defaultElementType);
return target;
}
//具體解析<list>集合元素,<array>盟广、<list>和<set>都使用該方法解析
protected void parseCollectionElements(
NodeList elementNodes, Collection<Object> target, @Nullable BeanDefinition bd, String defaultElementType) {
//遍歷集合所有節(jié)點
for (int i = 0; i < elementNodes.getLength(); i++) {
Node node = elementNodes.item(i);
//節(jié)點不是description節(jié)點
if (node instanceof Element && !nodeNameEquals(node, DESCRIPTION_ELEMENT)) {
//將解析的元素加入集合中闷串,遞歸調用下一個子元素
target.add(parsePropertySubElement((Element) node, bd, defaultElementType));
}
}
}
??SpringBean配置信息轉換的Document對象中的元素層層解析,SpringIOC現(xiàn)在已經將XML形式定義的Bean配置信息轉換為SpringIOC所識別的數(shù)據(jù)結構--->BeanDefinition衡蚂,它是Bean配置信息中配置的POJO對象在SpringIOC容器中的映射窿克。我們可以通過AbstractBeanDefinition為入口,看到lOC容器進行索引毛甲、查詢和操作年叮。
??SpringIOC容器對Bean配置資源的解析后,IOC容器大致完成了管理Bean對象的準備工作玻募,即初始化過程只损,但是最為重要的依賴注入還沒有發(fā)生,現(xiàn)在在IOC容器中BeanDefinition存儲的只是一些靜態(tài)信息七咧,接下來需要向容器注冊Bean定義信息才能全部完成IOC容器的初始化過程跃惫。
16.分配注冊策略
??DefaultBeanDefinitionDocumentReader對Bean定義轉換的Document對象解析的流程中,在其parseDefaultElement()
方法中完成對Document對象的解析得到BeanDefinition和BeanDefinitionHold對象艾栋。
然后調用BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
方法向IOC容器注冊解析Bean爆存,BeanDefinitionReaderUtils注冊的源碼是:
//將解析的BeanDefinitionHold注冊到容器中
public static void registerBeanDefinition(
BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
throws BeanDefinitionStoreException {
// Register bean definition under primary name.
//獲取解析的BeanDefinition的名稱
String beanName = definitionHolder.getBeanName();
//向IOC容器注冊BeanDefinition
registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
// Register aliases for bean name, if any.
//如果解析的BeanDefinition有別名,向容器為其注冊別名
String[] aliases = definitionHolder.getAliases();
if (aliases != null) {
for (String alias : aliases) {
registry.registerAlias(beanName, alias);
}
}
}
??DefaultListableBeanFactory中使用一個HashMap的集合對象存放IOC容器中注冊解析BeanDefinition蝗砾,向IOC容器注冊的主要源碼如下:
//向IOC容器注冊解析的BeanDefiniton
@Override
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");
//校驗解析的BeanDefiniton
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 (!isAllowBeanDefinitionOverriding()) {
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 (!beanDefinition.equals(oldBeanDefinition)) {
if (this.logger.isInfoEnabled()) {
this.logger.info("Overriding bean definition for bean '" + beanName +
"' with a different definition: replacing [" + oldBeanDefinition +
"] with [" + beanDefinition + "]");
}
}
else {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Overriding bean definition for bean '" + beanName +
"' with an equivalent definition: replacing [" + oldBeanDefinition +
"] with [" + beanDefinition + "]");
}
}
this.beanDefinitionMap.put(beanName, beanDefinition);
}
else {
if (hasBeanCreationStarted()) {
// Cannot modify startup-time collection elements anymore (for stable iteration)
//注冊的過程中需要線程同步先较,以保證數(shù)據(jù)的一致性
synchronized (this.beanDefinitionMap) {
this.beanDefinitionMap.put(beanName, beanDefinition);
List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
updatedDefinitions.addAll(this.beanDefinitionNames);
updatedDefinitions.add(beanName);
this.beanDefinitionNames = updatedDefinitions;
if (this.manualSingletonNames.contains(beanName)) {
Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
updatedSingletons.remove(beanName);
this.manualSingletonNames = updatedSingletons;
}
}
}
else {
// Still in startup registration phase
this.beanDefinitionMap.put(beanName, beanDefinition);
this.beanDefinitionNames.add(beanName);
this.manualSingletonNames.remove(beanName);
}
this.frozenBeanDefinitionNames = null;
}
//檢查是否有同名的BeanDefinition已經在IOC容器中注冊
if (oldBeanDefinition != null || containsSingleton(beanName)) {
//重置所有已經注冊過的BeanDefinition的緩存
resetBeanDefinition(beanName);
}
}
??Bean配置信息中的Bean被解析后,已經注冊到IOC容器中了悼粮,被容器管理起來了闲勺,真正完成了IOC容器初始化工作。現(xiàn)在IOC容器已經建立了整個Bean的配置信息扣猫,這些BeanDefinition信息已經可以使用菜循,并且可以檢索,IOC容器的作用就是對這些注冊的Bean定義信息進行處理和維護申尤。注冊的Bean定義信息是IOC容器控制反轉的基礎癌幕,正是有了這些注冊的數(shù)據(jù),容器才可以進行依賴注入瀑凝。