스프링 어 플 리 케 이 션 Context 로드 프로 세 스 상세 설명

1.입 구 를 정확하게 찾 고 ClassPathXmlapplicationContext 의 구조 방법 으로 프로필 을 불 러 옵 니 다.classPath 의 프로필 을 불 러 옵 니 다.

//   ,          spring       ,  spring   
ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext(
    "classpath:spring-mvc.xml");
//    Bean
Person person=context.getBean("person",Person.class);
2.ClassPathXmlApplication Context 구조 방법 소스 코드 는 다음 과 같다.

public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
   throws BeansException {
  //     ApplicationContext,null
  super(parent);
  //1.         , 2.         ${placeholder}         
  setConfigLocations(configLocations);
  if (refresh) {
   refresh();
  }
 }
3.주요 방법 은 setConfigLocation(configLocation)입 니 다.이 방법 은 부모 클래스 AbstractRefreshable ConfigApplication Context 의 방법 을 호출 합 니 다.

//locations :       
public void setConfigLocations(String[] locations) {
  if (locations != null) {
   //  
   Assert.noNullElements(locations, "Config locations must not be null");
   //           ,               
   this.configLocations = new String[locations.length];
   //  locations,     
   for (int i = 0; i < locations.length; i++) {
     //  resolvePath     
    this.configLocations[i] = resolvePath(locations[i]).trim();
   }
  }
  else {
   this.configLocations = null;
  }
 }
4.resovePath 의 소스 코드 에 들 어가 면 실제 적 으로 Abstract Property Resolver 의 doResolver Place holders 방법 을 실행 합 니 다.

/**
* text :        
* PropertyPlaceholderHelper :               ,                  
*/
private String doResolvePlaceholders(String text, PropertyPlaceholderHelper helper) {
  //  PropertyPlaceholderHelper   replacePlaceholders  
  return helper.replacePlaceholders(text, new PropertyPlaceholderHelper.PlaceholderResolver() {
   public String resolvePlaceholder(String placeholderName) {
    return getPropertyAsRawString(placeholderName);
   }
  });
 }
5.Property Helper 에 들 어 가 는 replacePlaceholder 방법 은 실제 적 으로 Property Placeholder Helper 의 parseStringValue 해석 자리 표시 자 를 호출 합 니 다.

public String replacePlaceholders(String value, PlaceholderResolver placeholderResolver) {
  Assert.notNull(value, "Argument 'value' must not be null.");
  //    parseStringValue  
  return parseStringValue(value, placeholderResolver, new HashSet<String>());
 }
 
/**
* strVal :         ,         
* placeholderResolver :     ,      
* visitedPlaceholders :            
**/
protected String parseStringValue(
   String strVal, PlaceholderResolver placeholderResolver, Set<String> visitedPlaceholders) {
  // strval   StringBuilder,       
  StringBuilder buf = new StringBuilder(strVal);
 
 //this.placeholderPrefix          ${,   PropertyHelper             placeholderPrefix="${" ,placeholderSuffix="}",valueSeparator=":"
 //                    
  int startIndex = strVal.indexOf(this.placeholderPrefix);
 
  while (startIndex != -1) {
   //              
   int endIndex = findPlaceholderEndIndex(buf, startIndex);
   
   //        
   if (endIndex != -1) {
    
    //    ${plcaeholder}       placeholder
    String placeholder = buf.substring(startIndex + this.placeholderPrefix.length(), endIndex);
    
    //           placeholder
    String originalPlaceholder = placeholder;
    
    //                ,       ,       
    if (!visitedPlaceholders.add(originalPlaceholder)) {
     throw new IllegalArgumentException(
       "Circular placeholder reference '" + originalPlaceholder + "' in property definitions");
    }
    
    //                 palceholder
    placeholder = parseStringValue(placeholder, placeholderResolver, visitedPlaceholders);
    
    
    //        ,        placeholder  ,   java.version   1.8.0_60
    String propVal = placeholderResolver.resolvePlaceholder(placeholder);
    
    if (propVal == null && this.valueSeparator != null) {
     int separatorIndex = placeholder.indexOf(this.valueSeparator);
     if (separatorIndex != -1) {
      String actualPlaceholder = placeholder.substring(0, separatorIndex);
      String defaultValue = placeholder.substring(separatorIndex + this.valueSeparator.length());
      propVal = placeholderResolver.resolvePlaceholder(actualPlaceholder);
      if (propVal == null) {
       propVal = defaultValue;
      }
     }
    }
    //             ,  ${java.version}      1.8.0_60
    if (propVal != null) {
     //         1.8.0_60     
     propVal = parseStringValue(propVal, placeholderResolver, visitedPlaceholders);
     //                 ,   ${java.version}     1.8.0_60
     buf.replace(startIndex, endIndex + this.placeholderSuffix.length(), propVal);
     if (logger.isTraceEnabled()) {
      logger.trace("Resolved placeholder '" + placeholder + "'");
     }
     //                    ,      ,           
     startIndex = buf.indexOf(this.placeholderPrefix, startIndex + propVal.length());
    }
    else if (this.ignoreUnresolvablePlaceholders) {
     // Proceed with unprocessed value.
     startIndex = buf.indexOf(this.placeholderPrefix, endIndex + this.placeholderSuffix.length());
    }
    else {
     throw new IllegalArgumentException("Could not resolve placeholder '" +
       placeholder + "'" + " in string value \"" + strVal + "\"");
    }
    //                      
    visitedPlaceholders.remove(originalPlaceholder);
   }
   else {
    startIndex = -1;
   }
  }
 
  return buf.toString(); //              
 }
6.그 다음 에 ClassPathXmlApplication Context 의 refresh 방법 입 니 다.실제 적 으로 부모 클래스 Abstract Application Context 방법 을 호출 합 니 다.

//  spring   
public void refresh() throws BeansException, IllegalStateException {
  synchronized (this.startupShutdownMonitor) {
   //           ,         ,          ,          ,         
   prepareRefresh();
 
   //    beanFactory,      beanFactory,    ,      10
   ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
 
   //        ,   12
   prepareBeanFactory(beanFactory);
 
   try {
    //              
    postProcessBeanFactory(beanFactory);
 
    //   BeanFactoryPostProcessor BeanDefintionRegistoryPostProcessor        
    invokeBeanFactoryPostProcessors(beanFactory);
 
    //   BeanPostProcessor,    bean   ,    14
    registerBeanPostProcessors(beanFactory);
 
    //      
    initMessageSource();
 
    //             ,              ,        ,            SimpleApplicationEventMulticaster
    initApplicationEventMulticaster();
 
    //          bean
    onRefresh();
 
    //        
    registerListeners();
 
    //          (non-lazy-init)
    finishBeanFactoryInitialization(beanFactory);
 
    //     ,          ......
    finishRefresh();
   }
 
   catch (BeansException ex) {
    // Destroy already created singletons to avoid dangling resources.
    destroyBeans();
 
    // Reset 'active' flag.
    cancelRefresh(ex);
 
    // Propagate exception to caller.
    throw ex;
   }
  }
 }
7,obtainFreshBeanFactory 진입 방법

//AbastractApplicationContext   
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
  //          ,                ,     loadBeanDefinitions(beanFactory);           BeanDefiniton 
  refreshBeanFactory();
  ConfigurableListableBeanFactory beanFactory = getBeanFactory();
  if (logger.isDebugEnabled()) {
   logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
  }
  return beanFactory;
 }
 
 
 //org.springframework.context.support.AbstractRefreshableApplicationContext    
 //AbstractApplicationContext       
 @Override
 protected final void refreshBeanFactory() throws BeansException {
  //     beanfactory,    
  if (hasBeanFactory()) {
   destroyBeans();
   closeBeanFactory();
  }
  
  try {
   //      beanFactory
   DefaultListableBeanFactory beanFactory = createBeanFactory();
   //     id
   beanFactory.setSerializationId(getId());
   
   //  beanFactory,      ,                         
   //  @Autowired @Qualifier,     QualifierAnnotationAutowireCandidateResolver
   customizeBeanFactory(beanFactory);
   //  BeanDefine     11
   loadBeanDefinitions(beanFactory);
   synchronized (this.beanFactoryMonitor) {
    this.beanFactory = beanFactory;
   }
  }
  catch (IOException ex) {
   throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
  }
 }
8.loadBeanDefinitions(beanFactory)에 들 어 가 는 방법

 //   org.springframework.context.support.AbstractXmlApplicationContext     
 protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
  
  //    beanDefinitionReader,    BeanDefinition
  XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
 
  //  XmlBeanDefinitionReader
  beanDefinitionReader.setEnvironment(this.getEnvironment());
  beanDefinitionReader.setResourceLoader(this); 
  beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
 
  initBeanDefinitionReader(beanDefinitionReader);
  //  BeanDefiniton,             BeanDefiniton       
  loadBeanDefinitions(beanDefinitionReader);
 }
9,prepareBeanFactory:준비 BeanFactory

//  BeanFactory,      ,       ,
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
  //      
  beanFactory.setBeanClassLoader(getClassLoader());
  
 //        ,    BeanDefiniton         
  beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
  
 
  beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
 
  //        ,        spring   bean        
  beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
  
  //        ,        @Resource  @Autowired        
  beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
  beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
  beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
  beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
  beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
  beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
 
  //           
  beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
  beanFactory.registerResolvableDependency(ResourceLoader.class, this);
  beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
  beanFactory.registerResolvableDependency(ApplicationContext.class, this);
 
  //            
  beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
 
  //        
  if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
   beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
 
   beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
  }
 
  //             ,  registerSingleton    ,                    
  if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
   beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
  }
  if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
   beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
  }
  if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
   beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
  }
 }
10.BeanFactory 의 백 엔 드 프로 세 서 를 호출 합 니 다.주요 기능 은 용기 에 등 록 된 BeanFactory PostProcessor 와 BeanDefinition Registory PostProcessor 를 호출 하 는 것 입 니 다.

//      BeanFactory     ,            
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
  //                 ,getBeanFactoryPostProcessors          BeanFactoryPostProcessor
  PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
 }
 
//       ,PostProcessorRegistrationDelegate    
public static void invokeBeanFactoryPostProcessors(
   ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
 
  // Invoke BeanDefinitionRegistryPostProcessors first, if any.
  Set<String> processedBeans = new HashSet<String>();
  
  //  beanFactory BeanDefinitionRegistry   ,BeanDefinitionRegistry          Bean     (BeanDefintion)
  if (beanFactory instanceof BeanDefinitionRegistry) {
   BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
   
   //  BeanFactoryPostProcessor
   List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
   
   //  BeanDefinitionRegistryPostProcessor
   List<BeanDefinitionRegistryPostProcessor> registryPostProcessors =
     new LinkedList<BeanDefinitionRegistryPostProcessor>();
   
   //  。     BeanDefinitionRegistryPostProcessor  
   for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
    if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
     BeanDefinitionRegistryPostProcessor registryPostProcessor =
       (BeanDefinitionRegistryPostProcessor) postProcessor;
     
      //  BeanDefinitionRegistryPostProcessor
     registryPostProcessor.postProcessBeanDefinitionRegistry(registry);
     //  
     registryPostProcessors.add(registryPostProcessor);
    }
    else {
     //     BeanFactoryPostProcessor  ,     
     regularPostProcessors.add(postProcessor);
    }
   }
 
   //---         beanFactory    BeanDefinitionRegistryPostProcessor bean       
   String[] postProcessorNames =
     beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
 
   // ----       BeanDefinitionRegistryPostProcessor        
   
   //    PriorityOrdered     BeanDefinitionRegistryPostProcessor
   List<BeanDefinitionRegistryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
   
   //  ,     PriorityOrdered         
   for (String ppName : postProcessorNames) {
    if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
     priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
     processedBeans.add(ppName);
    }
   }
   
   //       
   OrderComparator.sort(priorityOrderedPostProcessors);
   //      
   registryPostProcessors.addAll(priorityOrderedPostProcessors);
   
   //      PriorityOrdered     BeanDefinitionRegistryPostProcessor
   invokeBeanDefinitionRegistryPostProcessors(priorityOrderedPostProcessors, registry);
 
   // ----        Orderd     BeanDefinitionRegistryPostProcessor
   postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
   List<BeanDefinitionRegistryPostProcessor> orderedPostProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
   for (String ppName : postProcessorNames) {
    if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
     orderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
     processedBeans.add(ppName);
    }
   }
   OrderComparator.sort(orderedPostProcessors);
   registryPostProcessors.addAll(orderedPostProcessors);
   invokeBeanDefinitionRegistryPostProcessors(orderedPostProcessors, registry);
 
   
   // ----          BeanDefinitionRegistryPostProcessor
   
   boolean reiterate = true;
   while (reiterate) {
    reiterate = false;
    postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
    for (String ppName : postProcessorNames) {
     if (!processedBeans.contains(ppName)) {
      BeanDefinitionRegistryPostProcessor pp = beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class);
      registryPostProcessors.add(pp);
      processedBeans.add(ppName);
      pp.postProcessBeanDefinitionRegistry(registry);
      reiterate = true;
     }
    }
   }
 
   //   BeanFactoryPostProcessor      ,  BeanDefitionRegistory       
   invokeBeanFactoryPostProcessors(registryPostProcessors, beanFactory);
   invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
  }
 
  else {
   // Invoke factory processors registered with the context instance.
   invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
  }
 
  //---        BeanFactoryPostProcessor    ,        
  String[] postProcessorNames =
    beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
 
  // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
  // Ordered, and the rest.
  List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
  List<String> orderedPostProcessorNames = new ArrayList<String>();
  List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
  for (String ppName : postProcessorNames) {
   if (processedBeans.contains(ppName)) {
    // skip - already processed in first phase above
   }
   else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
    priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
   }
   else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
    orderedPostProcessorNames.add(ppName);
   }
   else {
    nonOrderedPostProcessorNames.add(ppName);
   }
  }
 
  // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
  OrderComparator.sort(priorityOrderedPostProcessors);
  invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
 
  // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
  List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
  for (String postProcessorName : orderedPostProcessorNames) {
   orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
  }
  OrderComparator.sort(orderedPostProcessors);
  invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
 
  // Finally, invoke all other BeanFactoryPostProcessors.
  List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
  for (String postProcessorName : nonOrderedPostProcessorNames) {
   nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
  }
  invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
 }
11.BeanPostProcessor 를 등록 하여 Bean 의 생 성 을 차단 합 니 다.이 인 터 페 이 스 는 Bean 초기 화 와 초기 화 후에 관련 작업 을 수행 할 수 있 습 니 다.

//         PostProcessorRegistrationDelegate,                       ,        
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
  PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
 }
 
//PostProcessorRegistrationDelegate    BeanPostProcessors   
//  beanFactory      beanFactory,   BeanPostProcessor     ,applicationContext        ,            
public static void registerBeanPostProcessors(
   ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
  
  //          BeanFactoryProcessor  ,
  String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
 
  //  BeanPostProcessor   
  int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
  beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
 
  // Separate between BeanPostProcessors that implement PriorityOrdered,
  // Ordered, and the rest.
  List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
  List<BeanPostProcessor> internalPostProcessors = new ArrayList<BeanPostProcessor>();
  List<String> orderedPostProcessorNames = new ArrayList<String>();
  List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
  for (String ppName : postProcessorNames) {
   if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
    BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
    priorityOrderedPostProcessors.add(pp);
    if (pp instanceof MergedBeanDefinitionPostProcessor) {
     internalPostProcessors.add(pp);
    }
   }
   else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
    orderedPostProcessorNames.add(ppName);
   }
   else {
    nonOrderedPostProcessorNames.add(ppName);
   }
  }
 
  // First, register the BeanPostProcessors that implement PriorityOrdered.
  OrderComparator.sort(priorityOrderedPostProcessors);
  registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
 
  // Next, register the BeanPostProcessors that implement Ordered.
  List<BeanPostProcessor> orderedPostProcessors = new ArrayList<BeanPostProcessor>();
  for (String ppName : orderedPostProcessorNames) {
   BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
   orderedPostProcessors.add(pp);
   if (pp instanceof MergedBeanDefinitionPostProcessor) {
    internalPostProcessors.add(pp);
   }
  }
  OrderComparator.sort(orderedPostProcessors);
  registerBeanPostProcessors(beanFactory, orderedPostProcessors);
 
  // Now, register all regular BeanPostProcessors.
  List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
  for (String ppName : nonOrderedPostProcessorNames) {
   BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
   nonOrderedPostProcessors.add(pp);
   if (pp instanceof MergedBeanDefinitionPostProcessor) {
    internalPostProcessors.add(pp);
   }
  }
  registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
 
  // Finally, re-register all internal BeanPostProcessors.
  OrderComparator.sort(internalPostProcessors);
  registerBeanPostProcessors(beanFactory, internalPostProcessors);
 
  beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
 }
이상 은 Spring Application Context 로 딩 과정 에 대한 상세 한 내용 입 니 다.Spring Application Context 로 딩 과정 에 관 한 자 료 는 다른 관련 글 을 주목 하 십시오!

좋은 웹페이지 즐겨찾기