Spring源码分析——基础组件解析

构架.png

核心组件接口分析

Resource

source结构.png

resource.png

加载资源方式

web服务器、请求远程资源http、可读写文件系统、Url统一资源定位符可以定位到几乎任何位置等待

策略.png

资源加载类ResourceLoader

根据路径得到资源,使用策略模式

public interface ResourceLoader {

   /** Pseudo URL prefix for loading from the class path: "classpath:". */
   String CLASSPATH_URL_PREFIX = ResourceUtils.CLASSPATH_URL_PREFIX;


   /**
    * Return a {@code Resource} handle for the specified resource location.
    * <p>The handle should always be a reusable resource descriptor,
    * allowing for multiple {@link Resource#getInputStream()} calls.
    * <p><ul>
    * <li>Must support fully qualified URLs, e.g. "file:C:/test.dat".
    * <li>Must support classpath pseudo-URLs, e.g. "classpath:test.dat".
    * <li>Should support relative file paths, e.g. "WEB-INF/test.dat".
    * (This will be implementation-specific, typically provided by an
    * ApplicationContext implementation.)
    * </ul>
    * <p>Note that a {@code Resource} handle does not imply an existing resource;
    * you need to invoke {@link Resource#exists} to check for existence.
    * @param location the resource location
    * @return a corresponding {@code Resource} handle (never {@code null})
    * @see #CLASSPATH_URL_PREFIX
    * @see Resource#exists()
    * @see Resource#getInputStream()
    */
   Resource getResource(String location);


   /**
    * Expose the {@link ClassLoader} used by this {@code ResourceLoader}.
    * <p>Clients which need to access the {@code ClassLoader} directly can do so
    * in a uniform manner with the {@code ResourceLoader}, rather than relying
    * on the thread context {@code ClassLoader}.
    * @return the {@code ClassLoader}
    * (only {@code null} if even the system {@code ClassLoader} isn't accessible)
    * @see org.springframework.util.ClassUtils#getDefaultClassLoader()
    * @see org.springframework.util.ClassUtils#forName(String, ClassLoader)
    */
   @Nullable
   ClassLoader getClassLoader();

}
复制代码

BeanFactory

jiagou.png

image.png GenericApplicationContext组合档案馆

public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {

   private final DefaultListableBeanFactory beanFactory;

   @Nullable
   private ResourceLoader resourceLoader;
}
复制代码

档案馆.png

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
      implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
    
    //组合模式,Spring里面可以有很多工厂。
    private static final Map<String, Reference<DefaultListableBeanFactory>> serializableFactories =
          new ConcurrentHashMap<>(8);
    }
    

    /** Map from dependency type to corresponding autowired value. */
    // 解析池子
    private final Map<Class<?>, Object> resolvableDependencies = new ConcurrentHashMap<>(16);

    /**如果容器中有Map<Class, Object[]/String[] ></> Map of bean definition objects, keyed by bean name. */
    //所有BeanDefinition信息按照名字对应BeanDefinition关系都保存好了。
    private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);

    /** Map from bean name to merged BeanDefinitionHolder. */
    private final Map<String, BeanDefinitionHolder> mergedBeanDefinitionHolders = new ConcurrentHashMap<>(256);

    /** Map of singleton and non-singleton bean names, keyed by dependency type. */
    private final Map<Class<?>, String[]> allBeanNamesByType = new ConcurrentHashMap<>(64);

    /** Map of singleton-only bean names, keyed by dependency type. */
    //Spring中按照类型得到组件的一个底层 池
       //车的图纸,String(cs75)--Class(图纸)只保存图纸(对象另说)
    private final Map<Class<?>, String[]> singletonBeanNamesByType = new ConcurrentHashMap<>(64);

    /** List of bean definition names, in registration order. */
    //保存所有BeanDefinition的名字。
    private volatile List<String> beanDefinitionNames = new ArrayList<>(256);
}
复制代码

注册bean定义中心BeanDefinitionRegistry

注册.png BeanDefinitionRegistry中注册beanDefaultListableBeanFactory

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
      implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
    @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");

       if (beanDefinition instanceof AbstractBeanDefinition) {
          try {
             ((AbstractBeanDefinition) beanDefinition).validate();
          }
          catch (BeanDefinitionValidationException ex) {
             throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
                   "Validation of bean definition failed", ex);
          }
       }

       BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
       if (existingDefinition != null) {
          if (!isAllowBeanDefinitionOverriding()) {
             throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
          }
          else if (existingDefinition.getRole() < beanDefinition.getRole()) {
             // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
             if (logger.isInfoEnabled()) {
                logger.info("Overriding user-defined bean definition for bean '" + beanName +
                      "' with a framework-generated bean definition: replacing [" +
                      existingDefinition + "] with [" + beanDefinition + "]");
             }
          }
          else if (!beanDefinition.equals(existingDefinition)) {
             if (logger.isDebugEnabled()) {
                logger.debug("Overriding bean definition for bean '" + beanName +
                      "' with a different definition: replacing [" + existingDefinition +
                      "] with [" + beanDefinition + "]");
             }
          }
          else {
             if (logger.isTraceEnabled()) {
                logger.trace("Overriding bean definition for bean '" + beanName +
                      "' with an equivalent definition: replacing [" + existingDefinition +
                      "] with [" + beanDefinition + "]");
             }
          }
          this.beanDefinitionMap.put(beanName, beanDefinition);
       }
       else {
          if (hasBeanCreationStarted()) {
             // Cannot modify startup-time collection elements anymore (for stable iteration)
             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;
                removeManualSingletonName(beanName);
             }
          }
          else {
             // Still in startup registration phase
             this.beanDefinitionMap.put(beanName, beanDefinition);
             this.beanDefinitionNames.add(beanName);
             removeManualSingletonName(beanName);
          }
          this.frozenBeanDefinitionNames = null;
       }

       if (existingDefinition != null || containsSingleton(beanName)) {
          resetBeanDefinition(beanName);
       }
       else if (isConfigurationFrozen()) {
          clearByTypeCache();
       }
    }
复制代码

Bean注册.png debug显示,在新建 Ioc容器的时候就会进入上述注册方法,因为注册时已经传了配置文件位置

public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
   this(new String[] {configLocation}, true, null);
}
复制代码

进入刷新方法

public abstract class AbstractRefreshableApplicationContext extends AbstractApplicationContext {

public ClassPathXmlApplicationContext(
      String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
      throws BeansException {

   super(parent);
   setConfigLocations(configLocations);
   if (refresh) {
      refresh(); // 刷新容器
   }
复制代码

创建容器的主要步骤就是刷新工厂

public abstract class AbstractApplicationContext extends DefaultResourceLoader
      implements ConfigurableApplicationContext {
      
    @Override
    public void refresh() throws BeansException, IllegalStateException {
       synchronized (this.startupShutdownMonitor) {

    // Tell the subclass to refresh the internal bean factory.
    ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();// BeanFactory第一次创建的时候
}

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
   refreshBeanFactory(); // 刷新工厂
   return getBeanFactory();
}
复制代码
public abstract class AbstractRefreshableApplicationContext extends AbstractApplicationContext {

    @Override
    protected final void refreshBeanFactory() throws BeansException {
       if (hasBeanFactory()) {
          destroyBeans();
          closeBeanFactory();
       }
       try {
       // 创建保存所有bean定义信息的档案馆
          DefaultListableBeanFactory beanFactory = createBeanFactory();
          beanFactory.setSerializationId(getId());
          customizeBeanFactory(beanFactory);
          loadBeanDefinitions(beanFactory);// 加载所有bean定义信息
          this.beanFactory = beanFactory;
       }
       catch (IOException ex) {
          throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
       }
    }
}
复制代码

loadBeanDefinitions加载所有bean定义信息,由于用xml配置,解析Xml文件

public abstract class AbstractXmlApplicationContext extends AbstractRefreshableConfigApplicationContext {
    @Override
    protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
       // Create a new XmlBeanDefinitionReader for the given BeanFactory.
       // 准备读取xml内容的读取器
       XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

       // Configure the bean definition reader with this context's
       // resource loading environment.
       beanDefinitionReader.setEnvironment(this.getEnvironment());
       beanDefinitionReader.setResourceLoader(this); // 持有Ioc容器的环境类
       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 loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
       Resource[] configResources = getConfigResources();
       if (configResources != null) {
          reader.loadBeanDefinitions(configResources);
       }
       String[] configLocations = getConfigLocations();// 可以一次传入很多配置文件
       if (configLocations != null) {
          reader.loadBeanDefinitions(configLocations);// 读取器加载所有Bean信息,读取文件
       }
    }
}
复制代码

读取器里面又组合了资源加载器

public abstract class AbstractBeanDefinitionReader implements BeanDefinitionReader, EnvironmentCapable {

    private final BeanDefinitionRegistry registry;

    @Nullable
    private ResourceLoader resourceLoader;

    @Nullable
    private ClassLoader beanClassLoader;

    private Environment environment;
    
    @Override // 加载指定配置文件的所有内容
    public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
       return loadBeanDefinitions(location, null);
    }

    
        @Override
        public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
           Assert.notNull(locations, "Location array must not be null");
           int count = 0;
           for (String location : locations) { // 加载每一个配置文件里的内容
              count += loadBeanDefinitions(location); // 递归调用
           }
           return count;
        }

    public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
       ResourceLoader resourceLoader = getResourceLoader();
       if (resourceLoader == null) {
          throw new BeanDefinitionStoreException(
                "Cannot load bean definitions from location [" + location + "]: no ResourceLoader available");
       }

       if (resourceLoader instanceof ResourcePatternResolver) {
          // Resource pattern matching available.
          try {
          // 策略模式只需要调用加载资源的策略就会得到这些实体文件对应的资源
          // ResourcePatternResolver被Ioc容器持有,Ioc容器又被BeanDefinitionReader持有
             Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
             int count = loadBeanDefinitions(resources);
             if (actualResources != null) {
                Collections.addAll(actualResources, resources);
             }
             if (logger.isTraceEnabled()) {
                logger.trace("Loaded " + count + " bean definitions from location pattern [" + location + "]");
             }
             return count;
          }
          catch (IOException ex) {
             throw new BeanDefinitionStoreException(
                   "Could not resolve bean definition resource pattern [" + location + "]", ex);
          }
       }
       else {
          // Can only load single resources by absolute URL.
          Resource resource = resourceLoader.getResource(location);
          int count = loadBeanDefinitions(resource);
          if (actualResources != null) {
             actualResources.add(resource);
          }
          if (logger.isTraceEnabled()) {
             logger.trace("Loaded " + count + " bean definitions from location [" + location + "]");
          }
          return count;
       }
    }
    
    
    @Override
    public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
    // 适配器模式 还传了Resource
       return loadBeanDefinitions(new EncodedResource(resource));
    }
}
复制代码
public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader {
    public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
       Assert.notNull(encodedResource, "EncodedResource must not be null");
       if (logger.isTraceEnabled()) {
          logger.trace("Loading XML bean definitions from " + encodedResource);
       }

       Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();

       if (!currentResources.add(encodedResource)) {
          throw new BeanDefinitionStoreException(
                "Detected cyclic loading of " + encodedResource + " - check your import definitions!");
       }

       try (InputStream inputStream = encodedResource.getResource().getInputStream()) {
          InputSource inputSource = new InputSource(inputStream);
          if (encodedResource.getEncoding() != null) {
             inputSource.setEncoding(encodedResource.getEncoding());
          }
          return doLoadBeanDefinitions(inputSource, encodedResource.getResource()); // 加载解析流
       }
       catch (IOException ex) {
          throw new BeanDefinitionStoreException(
                "IOException parsing XML document from " + encodedResource.getResource(), ex);
       }
       finally {
          currentResources.remove(encodedResource);
          if (currentResources.isEmpty()) {
             this.resourcesCurrentlyBeingLoaded.remove();
          }
       }
    }
    

    public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
       BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
       int countBefore = getRegistry().getBeanDefinitionCount();
       documentReader.registerBeanDefinitions(doc, createReaderContext(resource));// 调用documentReader解析
       return getRegistry().getBeanDefinitionCount() - countBefore;
    }
}
复制代码

适配器模式对接InputStreamSource和Resource

public class EncodedResource implements InputStreamSource {

    private final Resource resource;
    
  
    protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
          throws BeanDefinitionStoreException {

       try {
          Document doc = doLoadDocument(inputSource, resource); // 利用dom解析工具把xml变成Document
          int count = registerBeanDefinitions(doc, resource);
          if (logger.isDebugEnabled()) {
             logger.debug("Loaded " + count + " bean definitions from " + resource);
          }
          return count;
       }
       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);
       }
    }
}
复制代码

doc.png 逐个解析标签

public class DefaultBeanDefinitionDocumentReader implements BeanDefinitionDocumentReader {

    @Override
    public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
       this.readerContext = readerContext;
       doRegisterBeanDefinitions(doc.getDocumentElement()); // 拿到所有标签
    }

}
复制代码

解析document对象

public class DefaultBeanDefinitionDocumentReader implements BeanDefinitionDocumentReader {
        protected void doRegisterBeanDefinitions(Element root) {
       // Any nested <beans> elements will cause recursion in this method. In
       // order to propagate and preserve <beans> default-* attributes correctly,
       // keep track of the current (parent) delegate, which may be null. Create
       // the new (child) delegate with a reference to the parent for fallback purposes,
       // then ultimately reset this.delegate back to its original (parent) reference.
       // this behavior emulates a stack of delegates without actually necessitating one.
       BeanDefinitionParserDelegate parent = this.delegate;
       this.delegate = createDelegate(getReaderContext(), root, parent);

       if (this.delegate.isDefaultNamespace(root)) {
          String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
          if (StringUtils.hasText(profileSpec)) {
             String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
                   profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
             // We cannot use Profiles.of(...) since profile expressions are not supported
             // in XML config. See SPR-12458 for details.
             if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
                if (logger.isDebugEnabled()) {
                   logger.debug("Skipped XML bean definition file due to specified profiles [" + profileSpec +
                         "] not matching: " + getReaderContext().getResource());
                }
                return;
             }
          }
       }

       preProcessXml(root);
       parseBeanDefinitions(root, this.delegate); // 代理
       postProcessXml(root);

       this.delegate = parent;
    }

    protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
       if (delegate.isDefaultNamespace(root)) {
          NodeList nl = root.getChildNodes();
          for (int i = 0; i < nl.getLength(); i++) {
             Node node = nl.item(i);
             if (node instanceof Element) {
                Element ele = (Element) node;
                if (delegate.isDefaultNamespace(ele)) {
                   parseDefaultElement(ele, delegate); // 解析
                }
                else {
                   delegate.parseCustomElement(ele);
                }
             }
          }
       }
       else {
          delegate.parseCustomElement(root);
       }
    }


    private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
       if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
          importBeanDefinitionResource(ele);
       }
       else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
          processAliasRegistration(ele);
       }
       else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
       // 当前是bean标签,解析Bean标签
          processBeanDefinition(ele, delegate);
       }
       else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
          // recurse
          doRegisterBeanDefinitions(ele);
       }
    }


    protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
       BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
       if (bdHolder != null) {
          bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder); // 当前标签解析完了,Bean定义信息和Bean的名字都封装在holder,逐个标签进行解析
          try {
             // Register the final decorated instance.
             BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry()); // 利用工具类注册包装
          }
          catch (BeanDefinitionStoreException ex) {
             getReaderContext().error("Failed to register bean definition with name '" +
                   bdHolder.getBeanName() + "'", ele, ex);
          }
          // Send registration event. 
          // 发送一个通知事件
          getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
       }
    }

}
复制代码

BeanDefinitionParserDelegate里面存放解析标签方法和变量

解析.png 为了方便,把BeanDefinition和Name封装在一起

public class BeanDefinitionHolder implements BeanMetadataElement {

   private final BeanDefinition beanDefinition;

   private final String beanName;

   @Nullable
   private final String[] aliases;
}
复制代码

工具类

public abstract class BeanDefinitionReaderUtils {

    public static void registerBeanDefinition(
          BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
          throws BeanDefinitionStoreException {

       // Register bean definition under primary name.
       String beanName = definitionHolder.getBeanName();
       registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition()); // 最终回到断点位置

       // Register aliases for bean name, if any.
       String[] aliases = definitionHolder.getAliases();
       if (aliases != null) {
          for (String alias : aliases) {
             registry.registerAlias(beanName, alias);
          }
       }
    }

}
复制代码

最终回到断点位置

回来.png Ioc容器Application

在bean对象中拿到Ioc容器方法 直接注入

@Component
@Data
public class Person {

    @Autowired
    ApplicationContext context; // 可以要到ioc容器

    private String name;

    public Person() {
    }

    public Person(String name) {
        this.name = name;
    }

    // @Autowired // 依赖的组件是多实例就不能Autowired
    private Cat cat;

    @Lookup  //去容器中找。@Bean的这种方式注册的Person @Lookup不生效
    public Cat getCat(){
        return cat;
    }
    
}
复制代码

实现Aware接口\

package com.hong.spring.bean;

import lombok.Data;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.stereotype.Component;

/**
 * Aware接口;帮我们装配Spring底层的一些组件
 * 1、Bean的功能增强全部都是有 BeanPostProcessor+InitializingBean  (合起来完成的)
 * 2、骚操作就是 BeanPostProcessor+InitializingBean
 *
 * 你猜Autowired是怎么完成的
 * Person为什么能把ApplicationContext、MessageSource当为自己的参数传进来。
 *       - 通过实现接口的方式自动注入了 ApplicationContext、MessageSource。是由BeanPostProcessor(Bean的后置处理器完成的)
 */
@Component
@Data
public class Person implements ApplicationContextAware, MessageSourceAware {

//    @Autowired
    ApplicationContext context; // 可以要到ioc容器
    MessageSource messageSource;

    private String name;

    public Person() {
        System.out.println("person创建");
    }

    public Person(String name) {
        this.name = name;
    }

    // @Autowired // 依赖的组件是多实例就不能Autowired
    private Cat cat;

    @Autowired  //去发现一下.....
    public void setCat(Cat cat) {
        this.cat = cat;
    }

    @Lookup  //去容器中找。@Bean的这种方式注册的Person @Lookup不生效
    public Cat getCat(){
        return cat;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 利用回调机制把ioc容器传入
        this.context = applicationContext;
    }

    // 国际化工具
    @Override
    public void setMessageSource(MessageSource messageSource) {
        this.messageSource = messageSource;
    }
}
复制代码

在spring实例化bean的过程中,如果我们定义的bean实现了这些Aware,那么spring就会感知到这些Bean需要的东西

我们把断点打到构造器上面

package com.hong.spring.bean;

import lombok.Data;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.stereotype.Component;

/**
 * Aware接口;帮我们装配Spring底层的一些组件
 * 1、Bean的功能增强全部都是有 BeanPostProcessor+InitializingBean  (合起来完成的)
 * 2、骚操作就是 BeanPostProcessor+InitializingBean
 *
 * 你猜Autowired是怎么完成的
 * Person为什么能把ApplicationContext、MessageSource当为自己的参数传进来。
 *       - 通过实现接口的方式自动注入了 ApplicationContext、MessageSource。是由BeanPostProcessor(Bean的后置处理器完成的)
 */
@Component
@Data
public class Person implements ApplicationContextAware, MessageSourceAware {
    
    ApplicationContext context; // 可以要到ioc容器
    MessageSource messageSource;

    private String name;

    public Person() {
    }

    public Person(String name) {
        this.name = name;
    }

    // @Autowired // 依赖的组件是多实例就不能Autowired
    private Cat cat;

    @Lookup  //去容器中找。@Bean的这种方式注册的Person @Lookup不生效
    public Cat getCat(){
        return cat;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 利用回调机制把ioc容器传入
        this.context = applicationContext;
    }

    // 国际化工具
    @Override
    public void setMessageSource(MessageSource messageSource) {
        this.messageSource = messageSource;
    }
}
复制代码

刷新容器

public abstract class AbstractApplicationContext extends DefaultResourceLoader
      implements ConfigurableApplicationContext {

    @Override  //容器刷新的十二大步。模板模式
    public void refresh() throws BeansException, IllegalStateException {
       synchronized (this.startupShutdownMonitor) {
          StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");

          //准备上下文环境 Prepare this context for refreshing.
          prepareRefresh();

          // Tell the subclass to refresh the internal bean factory.
          // 工厂创建:BeanFactory第一次开始创建的时候,有xml解析逻辑。
          ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

          //给容器中注册了环境信息作为单实例Bean方便后续自动装配;放了一些后置处理器处理(监听、xxAware功能) Prepare the bean factory for use in this context.
          prepareBeanFactory(beanFactory);

          try {
             //留给子类的模板方法,允许子类继续对工厂执行一些处理; Allows post-processing of the bean factory in context subclasses.
             postProcessBeanFactory(beanFactory);

             StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
             //【大核心】工厂增强:执行所有的BeanFactory后置增强器;利用BeanFactory后置增强器对工厂进行修改或者增强,配置类会在这里进行解析。 Invoke factory processors registered as beans in the context.
             invokeBeanFactoryPostProcessors(beanFactory);

             //【核心】注册所有的Bean的后置处理器 Register bean processors that intercept bean creation.
             registerBeanPostProcessors(beanFactory);
             beanPostProcess.end();

             //初始化国际化功能 Initialize message source for this context.
             initMessageSource();

             //初始化事件多播功能(事件派发) Initialize event multicaster for this context.
             initApplicationEventMulticaster();

             // Initialize other special beans in specific context subclasses.
             onRefresh();

             //注册监听器,从容器中获取所有的ApplicationListener; Check for listener beans and register them.
             registerListeners();

             // Instantiate all remaining (non-lazy-init) singletons.
             //【大核心】bean创建;完成 BeanFactory 初始化。(工厂里面所有的组件都好了)
             finishBeanFactoryInitialization(beanFactory);

             //发布事件 Last step: publish corresponding event.
             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.
             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();
             contextRefresh.end();
          }
       }
    }
    
    

    /**
     * Finish the initialization of this context's bean factory,
     * initializing all remaining singleton beans.
     */
    protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
       // 给工厂设置好 ConversionService【负责类型转换的组件服务】, Initialize conversion service for this context.
       if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
             beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
          beanFactory.setConversionService(
                beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
       }

       // 注册一个默认的值解析器("${}")  ;Register a default embedded value resolver if no BeanFactoryPostProcessor
       // (such as a PropertySourcesPlaceholderConfigurer bean) registered any before:
       // at this point, primarily for resolution in annotation attribute values.
       if (!beanFactory.hasEmbeddedValueResolver()) {
          beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
       }

       // LoadTimeWeaverAware;aspectj:加载时织入功能【aop】。 Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
       String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
       for (String weaverAwareName : weaverAwareNames) {
          getBean(weaverAwareName); //从容器中获取组件,有则直接获取,没则进行创建
       }

       // Stop using the temporary ClassLoader for type matching.
       beanFactory.setTempClassLoader(null);

       // Allow for caching all bean definition metadata, not expecting further changes.
       beanFactory.freezeConfiguration();

       // Instantiate all remaining (non-lazy-init) singletons.
       //初始化所有的非懒加载的单实例Bean
       beanFactory.preInstantiateSingletons();
    }

}
复制代码

完成初始化

public class DefaultListableBeanFactory

@Override
public void preInstantiateSingletons() throws BeansException {
   if (logger.isTraceEnabled()) {
      logger.trace("Pre-instantiating singletons in " + this);
   }

   // Iterate over a copy to allow for init methods which in turn register new bean definitions.
   // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
   List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

   // 创建出所有的单实例Bean;Trigger initialization of all non-lazy singleton beans...
   for (String beanName : beanNames) {
      RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); //开始解析文件的时候每一个bean标签被解析封装成一个BeanDefinition
      if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
         if (isFactoryBean(beanName)) { //如果是FactoryBean则执行下面逻辑
            Object bean = getBean(FACTORY_BEAN_PREFIX + beanName); //得到HelloFactory
            if (bean instanceof FactoryBean) {
               FactoryBean<?> factory = (FactoryBean<?>) bean;
               boolean isEagerInit;
               if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                  isEagerInit = AccessController.doPrivileged(
                        (PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit,
                        getAccessControlContext());
               }
               else {
                  isEagerInit = (factory instanceof SmartFactoryBean &&
                        ((SmartFactoryBean<?>) factory).isEagerInit());
               }
               if (isEagerInit) {
                  getBean(beanName);
               }
            }
         }
         else { //不是FactoryBean则执行这个,普通的单实例非懒加载bean的创建
            getBean(beanName); //
         }
      }
   }
复制代码

getBean调用doGetBean

public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
    @Override
    public Object getBean(String name) throws BeansException {
       return doGetBean(name, null, null, false);
    }
    
    protected <T> T doGetBean(
          String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
          throws BeansException {

       String beanName = transformedBeanName(name); //转换Bean名字
       Object beanInstance;

       // 先检查单实例bean的缓存 Eagerly check singleton cache for manually registered singletons.
       Object sharedInstance = getSingleton(beanName); //检查缓存中有没有,如果是第一次获取肯定是没有的
       if (sharedInstance != null && args == null) {
          if (logger.isTraceEnabled()) {
             if (isSingletonCurrentlyInCreation(beanName)) {
                logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
                      "' that is not fully initialized yet - a consequence of a circular reference");
             }
             else {
                logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
             }
          }
          beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, null);
       }

       else { //默认第一次获取组件都会进入else环节
          // Fail if we're already creating this bean instance:
          // We're assumably within a circular reference.
          if (isPrototypeCurrentlyInCreation(beanName)) {
             throw new BeanCurrentlyInCreationException(beanName);
          }

          // 拿到整个beanFactory的父工厂;看父工厂没有,从父工厂先尝试获取组件; Check if bean definition exists in this factory.
          BeanFactory parentBeanFactory = getParentBeanFactory();
          if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { //以下开始从父工厂获取组件
             // Not found -> check parent.
             String nameToLookup = originalBeanName(name);
             if (parentBeanFactory instanceof AbstractBeanFactory) {
                return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
                      nameToLookup, requiredType, args, typeCheckOnly);
             }
             else if (args != null) {
                // Delegation to parent with explicit args.
                return (T) parentBeanFactory.getBean(nameToLookup, args);
             }
             else if (requiredType != null) {
                // No args -> delegate to standard getBean method.
                return parentBeanFactory.getBean(nameToLookup, requiredType);
             }
             else {
                return (T) parentBeanFactory.getBean(nameToLookup);
             }
          }

          if (!typeCheckOnly) {
             markBeanAsCreated(beanName); //标记当前beanName的bean已经被创建
          }

          StartupStep beanCreation = this.applicationStartup.start("spring.beans.instantiate")
                .tag("beanName", name);
          try {
             if (requiredType != null) {
                beanCreation.tag("beanType", requiredType::toString);
             }
             RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
             checkMergedBeanDefinition(mbd, beanName, args);

             // Guarantee initialization of beans that the current bean depends on.
             String[] dependsOn = mbd.getDependsOn();
             if (dependsOn != null) {
                for (String dep : dependsOn) { //看当前Bean有没有依赖其他Bean
                   if (isDependent(beanName, dep)) {
                      throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                            "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
                   }
                   registerDependentBean(dep, beanName);
                   try {
                      getBean(dep); //依赖了其他bean,就先获取其他的哪些bean
                   }
                   catch (NoSuchBeanDefinitionException ex) {
                      throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                            "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
                   }
                }
             }

             // 创建bean的实例;Create bean instance.
             if (mbd.isSingleton()) {
                sharedInstance = getSingleton(beanName, () -> {
                   try {
                      return createBean(beanName, mbd, args);  //创建bean对象的实例
                   }
                   catch (BeansException ex) {
                      // Explicitly remove instance from singleton cache: It might have been put there
                      // eagerly by the creation process, to allow for circular reference resolution.
                      // Also remove any beans that received a temporary reference to the bean.
                      destroySingleton(beanName);
                      throw ex;
                   }
                }); //看当前bean是否是FactoryBean
                beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
             }

             else if (mbd.isPrototype()) {
                // It's a prototype -> create a new instance.
                Object prototypeInstance = null;
                try {
                   beforePrototypeCreation(beanName);
                   prototypeInstance = createBean(beanName, mbd, args);
                }
                finally {
                   afterPrototypeCreation(beanName);
                }
                beanInstance = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
             }

             else {
                String scopeName = mbd.getScope();
                if (!StringUtils.hasLength(scopeName)) {
                   throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
                }
                Scope scope = this.scopes.get(scopeName);
                if (scope == null) {
                   throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
                }
                try {
                   Object scopedInstance = scope.get(beanName, () -> {
                      beforePrototypeCreation(beanName);
                      try {
                         return createBean(beanName, mbd, args);
                      }
                      finally {
                         afterPrototypeCreation(beanName);
                      }
                   });
                   beanInstance = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                }
                catch (IllegalStateException ex) {
                   throw new ScopeNotActiveException(beanName, scopeName, ex);
                }
             }
          }
          catch (BeansException ex) {
             beanCreation.tag("exception", ex.getClass().toString());
             beanCreation.tag("message", String.valueOf(ex.getMessage()));
             cleanupAfterBeanCreationFailure(beanName);
             throw ex;
          }
          finally {
             beanCreation.end();
          }
       }
       //转Object为Bean的T类型
       return adaptBeanInstance(name, beanInstance, requiredType);
    }

}
复制代码

该类里面就是Ioc容器。检查单例缓存池,获取当前对象

public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {

    /** 享元模式的单例。缓存所有单实例对象,单例对象池。ioc容器-单例池; Cache of singleton objects: bean name to bean instance. */
    private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

    /** Cache of singleton factories: bean name to ObjectFactory. */
    private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);

    /** Cache of early singleton objects: bean name to bean instance. */
    private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<>(16);

    /** Set of registered singletons, containing the bean names in registration order. */
    private final Set<String> registeredSingletons = new LinkedHashSet<>(256);
    

    /**
     * Return the (raw) singleton object registered under the given name.
     * <p>Checks already instantiated singletons and also allows for an early
     * reference to a currently created singleton (resolving a circular reference).
     * @param beanName the name of the bean to look for
     * @param allowEarlyReference whether early references should be created or not
     * @return the registered singleton object, or {@code null} if none found
     */
    @Nullable  //双检查锁
    protected Object getSingleton(String beanName, boolean allowEarlyReference) {
       //先检查单例缓存池,获取当前对象  Quick check for existing instance without full singleton lock
       Object singletonObject = this.singletonObjects.get(beanName); //一级缓存
       if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) { //如果当前bean正在创建过程中,而且缓存中没有则继续
          singletonObject = this.earlySingletonObjects.get(beanName); //二级
          if (singletonObject == null && allowEarlyReference) {
             synchronized (this.singletonObjects) {
                // Consistent creation of early reference within full singleton lock
                singletonObject = this.singletonObjects.get(beanName);
                if (singletonObject == null) {
                   singletonObject = this.earlySingletonObjects.get(beanName);
                   if (singletonObject == null) {
                      ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName); //三级
                      if (singletonFactory != null) {
                         singletonObject = singletonFactory.getObject();
                         this.earlySingletonObjects.put(beanName, singletonObject);
                         this.singletonFactories.remove(beanName);
                      }
                   }
                }
             }
          }
       }
       return singletonObject;
    }
    
}
复制代码

这里用到策略模式,拿到bean对象后,用代理对象反射来创建实例对象。后面就是通过反射获取注解并且赋值,实现AutoWired 代理策略.png

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
      implements AutowireCapableBeanFactory {

   /** 指定Bean的创建策略;可以用jdk的反射,可以用cglib创建子类对象 Strategy for creating bean instances. */
   private InstantiationStrategy instantiationStrategy;
   

    /** 创建对象
     * Central method of this class: creates a bean instance,
     * populates the bean instance, applies post-processors, etc.
     * @see #doCreateBean
     */
    @Override
    protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
          throws BeanCreationException {

       if (logger.isTraceEnabled()) {
          logger.trace("Creating instance of bean '" + beanName + "'");
       }
       RootBeanDefinition mbdToUse = mbd;

       // Make sure bean class is actually resolved at this point, and
       // clone the bean definition in case of a dynamically resolved Class
       // which cannot be stored in the shared merged bean definition.
       Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
       if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
          mbdToUse = new RootBeanDefinition(mbd);
          mbdToUse.setBeanClass(resolvedClass);
       }

       // Prepare method overrides.
       try {
          mbdToUse.prepareMethodOverrides();
       }
       catch (BeanDefinitionValidationException ex) {
          throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
                beanName, "Validation of method overrides failed", ex);
       }

       try {
          //(即使AOP的BeanPostProcessor都不会珍惜这个机会) 提前给我们一个机会,去返回组件的代理对象。 Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
          Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
          if (bean != null) {
             return bean;
          }
       }
       catch (Throwable ex) {
          throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
                "BeanPostProcessor before instantiation of bean failed", ex);
       }

       try { //Spring真正自己创建对象
          Object beanInstance = doCreateBean(beanName, mbdToUse, args);
          if (logger.isTraceEnabled()) {
             logger.trace("Finished creating instance of bean '" + beanName + "'");
          }
          return beanInstance;
       }
       catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
          // A previously detected exception with proper bean creation context already,
          // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
          throw ex;
       }
       catch (Throwable ex) {
          throw new BeanCreationException(
                mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
       }
    }
    
    /**
     * Actually create the specified bean. Pre-creation processing has already happened
     * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
     * <p>Differentiates between default bean instantiation, use of a
     * factory method, and autowiring a constructor.
     * @param beanName the name of the bean
     * @param mbd the merged bean definition for the bean
     * @param args explicit arguments to use for constructor or factory method invocation
     * @return a new instance of the bean
     * @throws BeanCreationException if the bean could not be created
     * @see #instantiateBean
     * @see #instantiateUsingFactoryMethod
     * @see #autowireConstructor
     */
    protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
          throws BeanCreationException {

       // Instantiate the bean.
       BeanWrapper instanceWrapper = null;
       if (mbd.isSingleton()) { //是否单例的
          instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
       }
       if (instanceWrapper == null) {
          //创建Bean的实例,默认使用无参构造器创建的对象,组件的原始对象就创建了
          instanceWrapper = createBeanInstance(beanName, mbd, args);
       }
       Object bean = instanceWrapper.getWrappedInstance();
       Class<?> beanType = instanceWrapper.getWrappedClass();
       if (beanType != NullBean.class) {
          mbd.resolvedTargetType = beanType;
       }

       //允许 后置处理器 再来修改下beanDefinition;MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition;;   Allow post-processors to modify the merged bean definition.
       synchronized (mbd.postProcessingLock) {
          if (!mbd.postProcessed) {
             try {
                applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
             }
             catch (Throwable ex) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                      "Post-processing of merged bean definition failed", ex);
             }
             mbd.postProcessed = true;
          }
       }

       // 提前暴露单实例。专门来解决循环引用问题;Eagerly cache singletons to be able to resolve circular references
       // even when triggered by lifecycle interfaces like BeanFactoryAware.
       boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
             isSingletonCurrentlyInCreation(beanName));
       if (earlySingletonExposure) {
          if (logger.isTraceEnabled()) {
             logger.trace("Eagerly caching bean '" + beanName +
                   "' to allow for resolving potential circular references");
          }
          addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); //三级缓存中的Bean也会被后置处理来增强,
       }

       // Initialize the bean instance.
       Object exposedObject = bean;
       try {
          populateBean(beanName, mbd, instanceWrapper); //给创建好的对象每个属性进行赋值,@Autowired发生在这里
          exposedObject = initializeBean(beanName, exposedObject, mbd);//初始化bean
       }
       catch (Throwable ex) {
          if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
             throw (BeanCreationException) ex;
          }
          else {
             throw new BeanCreationException(
                   mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
          }
       }
       //早期单实例暴露
       if (earlySingletonExposure) {
          Object earlySingletonReference = getSingleton(beanName, false); //检查早期缓存中是否存在这个组件
          if (earlySingletonReference != null) {
             if (exposedObject == bean) {
                exposedObject = earlySingletonReference;
             }
             else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                String[] dependentBeans = getDependentBeans(beanName);
                Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
                for (String dependentBean : dependentBeans) {
                   if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                      actualDependentBeans.add(dependentBean);
                   }
                }
                if (!actualDependentBeans.isEmpty()) {
                   throw new BeanCurrentlyInCreationException(beanName,
                         "Bean with name '" + beanName + "' has been injected into other beans [" +
                         StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
                         "] in its raw version as part of a circular reference, but has eventually been " +
                         "wrapped. This means that said other beans do not use the final version of the " +
                         "bean. This is often the result of over-eager type matching - consider using " +
                         "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
                }
             }
          }
       }
       

    /**
     * Initialize the given bean instance, applying factory callbacks
     * as well as init methods and bean post processors.
     * <p>Called from {@link #createBean} for traditionally defined beans,
     * and from {@link #initializeBean} for existing bean instances.
     * @param beanName the bean name in the factory (for debugging purposes)
     * @param bean the new bean instance we may need to initialize
     * @param mbd the bean definition that the bean was created with
     * (can also be {@code null}, if given an existing bean instance)
     * @return the initialized bean instance (potentially wrapped)
     * @see BeanNameAware
     * @see BeanClassLoaderAware
     * @see BeanFactoryAware
     * @see #applyBeanPostProcessorsBeforeInitialization
     * @see #invokeInitMethods
     * @see #applyBeanPostProcessorsAfterInitialization
     */
    protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
       if (System.getSecurityManager() != null) {
          AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
             invokeAwareMethods(beanName, bean);
             return null;
          }, getAccessControlContext());
       }
       else {
          invokeAwareMethods(beanName, bean); //组件有Aware接口,先Aware;BeanNameAware、BeanClassLoaderAware、BeanFactoryAware
       }

       Object wrappedBean = bean;
       if (mbd == null || !mbd.isSynthetic()) {//执行后置处理器的BeforeInitialization方法
          wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
       }

       try {
          invokeInitMethods(beanName, wrappedBean, mbd);
       }
       catch (Throwable ex) {
          throw new BeanCreationException(
                (mbd != null ? mbd.getResourceDescription() : null),
                beanName, "Invocation of init method failed", ex);
       }
       if (mbd == null || !mbd.isSynthetic()) { //
          wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
       }

       return wrappedBean;
    }
    
    
   
    @Override
    public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
          throws BeansException {

       Object result = existingBean;
       for (BeanPostProcessor processor : getBeanPostProcessors()) {
          Object current = processor.postProcessBeforeInitialization(result, beanName);
          if (current == null) { //不管null的东西
             return result;
          }
          result = current;
       }
       return result;
    }


    /**
     * Populate the bean instance in the given BeanWrapper with the property values
     * from the bean definition.
     * @param beanName the name of the bean
     * @param mbd the bean definition for the bean
     * @param bw the BeanWrapper with bean instance
     */
    @SuppressWarnings("deprecation")  // for postProcessPropertyValues
    protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
       if (bw == null) {
          if (mbd.hasPropertyValues()) {
             throw new BeanCreationException(
                   mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
          }
          else {
             // Skip property population phase for null instance.
             return;
          }
       }

       // @Autowired赋值也在这里(但是没做事)。可以中断初始化行为; 在属性赋值之前,后置处理器可以提前准备些东西 Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
       // state of the bean before properties are set. This can be used, for example,
       // to support styles of field injection.
       if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
          for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
             if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                return;
             }
          }
       } //以上的后置处理器可以中断以下的行为

       PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

       int resolvedAutowireMode = mbd.getResolvedAutowireMode();
       if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
          MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
          // Add property values based on autowire by name if applicable.
          if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
             autowireByName(beanName, mbd, bw, newPvs);
          }
          // Add property values based on autowire by type if applicable.
          if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
             autowireByType(beanName, mbd, bw, newPvs);
          }
          pvs = newPvs;
       }

       boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
       boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

       PropertyDescriptor[] filteredPds = null;
       if (hasInstAwareBpps) {
          if (pvs == null) {
             pvs = mbd.getPropertyValues(); //xml中property标签指定的
          } //使用后置处理器处理属性
          for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
             PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
             if (pvsToUse == null) {
                if (filteredPds == null) {
                   filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                }
                pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                if (pvsToUse == null) {
                   return;
                }
             }
             pvs = pvsToUse; //封装了当前bean的所有属性名和值,可以由后置处理器处理得到
          }
       }
       if (needsDepCheck) {
          if (filteredPds == null) {
             filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
          }
          checkDependencies(beanName, mbd, filteredPds, pvs);
       }

       if (pvs != null) { //把以前处理好的PropertyValues给bean里面设置一下。主要是上面步骤没有给bean里面设置的属性
          applyPropertyValues(beanName, mbd, bw, pvs); //xml版的所有配置会来到这里给属性赋值
       }
    }


    /**
     * Apply the given property values, resolving any runtime references
     * to other beans in this bean factory. Must use deep copy, so we
     * don't permanently modify this property.
     * @param beanName the bean name passed for better exception information
     * @param mbd the merged bean definition
     * @param bw the BeanWrapper wrapping the target object
     * @param pvs the new property values
     */
    protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
       if (pvs.isEmpty()) {
          return;
       }

       if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
          ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
       }

       MutablePropertyValues mpvs = null;
       List<PropertyValue> original;

       if (pvs instanceof MutablePropertyValues) {
          mpvs = (MutablePropertyValues) pvs;
          if (mpvs.isConverted()) {
             // Shortcut: use the pre-converted values as-is.
             try {
                bw.setPropertyValues(mpvs);
                return;
             }
             catch (BeansException ex) {
                throw new BeanCreationException(
                      mbd.getResourceDescription(), beanName, "Error setting property values", ex);
             }
          }
          original = mpvs.getPropertyValueList();
       }
       else {
          original = Arrays.asList(pvs.getPropertyValues());
       }

       TypeConverter converter = getCustomTypeConverter();
       if (converter == null) {
          converter = bw;
       }
       BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);

       // Create a deep copy, resolving any references for values.
       List<PropertyValue> deepCopy = new ArrayList<>(original.size());
       boolean resolveNecessary = false;
       for (PropertyValue pv : original) {
          if (pv.isConverted()) {
             deepCopy.add(pv);
          }
          else {
             String propertyName = pv.getName();
             Object originalValue = pv.getValue();
             if (originalValue == AutowiredPropertyMarker.INSTANCE) {
                Method writeMethod = bw.getPropertyDescriptor(propertyName).getWriteMethod();
                if (writeMethod == null) {
                   throw new IllegalArgumentException("Autowire marker for property without write method: " + pv);
                }
                originalValue = new DependencyDescriptor(new MethodParameter(writeMethod, 0), true);
             }
             Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
             Object convertedValue = resolvedValue;
             boolean convertible = bw.isWritableProperty(propertyName) &&
                   !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
             if (convertible) {
                convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
             }
             // Possibly store converted value in merged bean definition,
             // in order to avoid re-conversion for every created bean instance.
             if (resolvedValue == originalValue) {
                if (convertible) {
                   pv.setConvertedValue(convertedValue);
                }
                deepCopy.add(pv);
             }
             else if (convertible && originalValue instanceof TypedStringValue &&
                   !((TypedStringValue) originalValue).isDynamic() &&
                   !(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
                pv.setConvertedValue(convertedValue);
                deepCopy.add(pv);
             }
             else {
                resolveNecessary = true;
                deepCopy.add(new PropertyValue(pv, convertedValue));
             }
          }
       }
       if (mpvs != null && !resolveNecessary) {
          mpvs.setConverted();
       }

       // Set our (possibly massaged) deep copy.
       try { //深拷贝所有PropertyValue应该对应的属性
          bw.setPropertyValues(new MutablePropertyValues(deepCopy));
       }
       catch (BeansException ex) {
          throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, "Error setting property values", ex);
       }
    }


}
复制代码

aware.png 后置处理器

class ApplicationContextAwareProcessor implements BeanPostProcessor {

    @Override
    @Nullable
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
       if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
             bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
             bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware ||
             bean instanceof ApplicationStartupAware)) {
          return bean;
       }

       AccessControlContext acc = null;

       if (System.getSecurityManager() != null) {
          acc = this.applicationContext.getBeanFactory().getAccessControlContext();
       }

       if (acc != null) {
          AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
             invokeAwareInterfaces(bean);
             return null;
          }, acc);
       }
       else {
          invokeAwareInterfaces(bean); //执行aware接口规定的方法
       }

       return bean;
    }
    
  
    private void invokeAwareInterfaces(Object bean) {
       if (bean instanceof EnvironmentAware) {
          ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
       }
       if (bean instanceof EmbeddedValueResolverAware) {
          ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
       }
       if (bean instanceof ResourceLoaderAware) {
          ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
       }
       if (bean instanceof ApplicationEventPublisherAware) {
          ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
       }
       if (bean instanceof MessageSourceAware) { //利用多态的特性调用相关方法注入值
          ((MessageSourceAware) bean).setMessageSource(this.applicationContext);
       }
       if (bean instanceof ApplicationStartupAware) {
          ((ApplicationStartupAware) bean).setApplicationStartup(this.applicationContext.getApplicationStartup());
       }
       if (bean instanceof ApplicationContextAware) {
          ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
       }
    }
}
复制代码

结束

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    // 利用回调机制把ioc容器传入
    this.context = applicationContext;
}
复制代码

DefaultSingletonBeanRegistry既是图纸(Bean)的储存中心也是飞机(Bean的实例)的

PropertyValues迭代器模式

public interface PropertyValues extends Iterable<PropertyValue> {

   /** PropertyValue指的是一个属性的键值对。属性名和属性值
    * Return an {@link Iterator} over the property values.
    * @since 5.1
    */
   @Override
   default Iterator<PropertyValue> iterator() {
      return Arrays.asList(getPropertyValues()).iterator();
   }
}
复制代码

猜你喜欢

转载自juejin.im/post/7084135358325063688
今日推荐