天天看點

Spring源碼學習--XmlWebApplicationContext(四)

ApplicationContext應用上下文體系如下:

Spring源碼學習--XmlWebApplicationContext(四)
public class XmlWebApplicationContext extends AbstractRefreshableWebApplicationContext {
  /** 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";
  //解析applicationContext.xml
  @Override
  protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
    // Create a new XmlBeanDefinitionReader for the given BeanFactory.
    XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
    // Configure the bean definition reader with this context's
    // resource loading environment.
    beanDefinitionReader.setEnvironment(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);
  }
  protected void initBeanDefinitionReader(XmlBeanDefinitionReader beanDefinitionReader) {
  }
  protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws IOException {
    String[] configLocations = getConfigLocations();
    if (configLocations != null) {
      for (String configLocation : configLocations) {
        reader.loadBeanDefinitions(configLocation);
      }
    }
  }
  //擷取預設配置檔案位址
  @Override
  protected String[] getDefaultConfigLocations() {
    if (getNamespace() != null) {
      return new String[] {DEFAULT_CONFIG_LOCATION_PREFIX + getNamespace() + DEFAULT_CONFIG_LOCATION_SUFFIX};
    }
    else {
      return new String[] {DEFAULT_CONFIG_LOCATION};
    }
  }
}