Deep understanding of Spring Series 4: BeanDefinition loading prelude,

Source: Internet
Author: User

Deep understanding of Spring Series 4: BeanDefinition loading prelude,

Framework source code analysis, some code can be temporarily ignored, such as how Spring performs XML Schema validation, XML parsing details, etc. After learning about the overall principles of these code, then perform targeted analysis and focus on the key content. Remember to dig deep into every detail at the beginning, which will not only take a long time, but also easily fall into a certain trap.

Take ApplicationContext applicationContext = new ClassPathXmlApplicationContext ("applicationgContext. xml") in the example of "understanding one of the Spring Series: Beginning" as the portal to enter the source code. The ClassPathXmlApplicationContext class diagram is as follows.

ClassPathXmlApplicationContext has multiple constructor methods. You can trace the code to find that the following method is used in the end,

public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)      throws BeansException {    super(parent);    setConfigLocations(configLocations);    if (refresh) {      refresh();    }}

The parameters of the method are easy to understand. configLocations refer to the xml configuration file of Spring; refresh refers to whether to refresh; this refresh determines whether to parse, register, and instantiate bean; parent refers to the parent ApplicationContext. The setConfigLocations method is used to set the location of the resource file to be loaded by the framework. Enter the refresh method, which inherits from AbstractApplicationContext. Therefore, the specific implementation is in the AbstractApplicationContext class. The specific code is as follows.

Public void refresh () throws BeansException, IllegalStateException {synchronized (this. startupShutdownMonitor) {// container preparation, record the container startup time and Mark prepareRefresh (); // create a bean Factory, which implements BeanDefinition loading, and implements descriablelistablebeanfactory beanFactory = obtainFreshBeanFactory (); // configure the context information of the bean Factory, such as prepareBeanFactory (beanFactory). try {// After BeanDefinition is loaded, provide the postProcessBeanFactory (BeanFactory) entry for modifying beanFactory ); // The BeanDefinition modification entry is provided before bean initialization. propertyplaceholderholder is called invokeBeanFactoryPostProcessors (beanFactory) here; // register various BeanPostProcessors for blocking bean initialization, perform additional initialization operations registerBeanPostProcessors (beanFactory); // initialize MessageSource initMessageSource (); // initialize context event broadcast initApplicationEventMulticaster (); // template method onRefresh (); // register the listener registerListeners (); // Initialize all uninitialized non-Lazy loaded Singleton BeanfinishBeanFactoryInitialization (beanFactory); // publish Event Notification finishRefresh ();} catch (BeansException ex) {if (logger. isWarnEnabled () {logger. warn ("Exception encountered during context initialization-" + "canceling refresh attempt:" + ex);} // Destroy already created singletons to avoid dangling resources. destroyBeans (); // Reset 'active' flag. cancelRefresh (ex); // Propagate exception to caller. throw ex;} finally {// Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches ();}}}

In this method, the IOC container initialization steps are outlined. The second step of the preceding step completes BeanDefinition loading and enters the obtainFreshBeanFactory method. The specific implementation of this method is also in the AbstractApplicationContext class. The Code is as follows.

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {    refreshBeanFactory();    ConfigurableListableBeanFactory beanFactory = getBeanFactory();if (logger.isDebugEnabled()) {      logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);    }    return beanFactory;}

Here we mainly focus on the refreshBeanFactory method. This method is not implemented in the AbstractApplicationContext class. The Code is as follows in the subclass AbstractRefreshableApplicationContext.

protected final void refreshBeanFactory() throws BeansException {    if (hasBeanFactory()) {      destroyBeans();closeBeanFactory();    }    try {      DefaultListableBeanFactory beanFactory = createBeanFactory();      beanFactory.setSerializationId(getId());      customizeBeanFactory(beanFactory);      loadBeanDefinitions(beanFactory);      synchronized (this.beanFactoryMonitor) {        this.beanFactory = beanFactory;      }    }    catch (IOException ex) {      throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);    }}

This method uses final modification, that is, it cannot be overwritten. First, check whether BeanFactory exists. If BeanFactory exists, destroy and close it. Then, create a BeanFactory, which is actually a DefaultListableBeanFactory. The defalistlistablebeanfactory is the one in Spring Series: the one mentioned in the beginning. Then, set the BeanFactory attribute to determine whether to allow rewriting of BeanDefinition and whether to allow loop reference. Then, the loadBeanDefinitions method is the entry to BeanDefinition loading. This method is not implemented in the AbstractRefreshableApplicationContext class, specifically, there are multiple implementation subclasses based on different purposes. The next article will analyze the implementation in the AbstractXmlApplicationContext Class Based on the basic parsing xml method.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.