三Spring-ioc容器--2解析、扫描、注册源码分析

三Spring-ioc容器--2解析、扫描、注册源码分析

3.3.1.2.1 默认bean解析

DefaultBeanDefinitionDocumentReader.parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate)

该类作用:(自定义标签解析,用BeanDefinitionParserDelegate类内的方法)

({@link BeanDefinitionDocumentReader} 接口的默认实现,该接口根据“spring-beans”DTD 和 XSD 格式(Spring 的默认 XML bean 定义格式)读取 bean 定义。)

	private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
		if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
			importBeanDefinitionResource(ele);
		}
		else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
			processAliasRegistration(ele);
		}
          //bean标签的解析
		else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
			processBeanDefinition(ele, delegate);
		}
    //处理嵌套bean的元素,采用迭代方法,继续调用doRegisterBeanDefinitions
		else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
			// recurse
			doRegisterBeanDefinitions(ele);
		}
	}
	// 处理给定的bean element,解析beandefinition,并在registry中注册
	protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
          //解析document元素标签,并封装成beandefinitionHolder
          //标签元素解析的主要过程
//TAG1 delegate.parseBeanDefinitionElement(ele)
		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
		if (bdHolder != null) {
               //对解析结果进行装饰,动态添加其他功能
//TAG2 delegate.decorateBeanDefinitionIfRequired(ele, bdHolder)
			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
			try {
//TAG3 readerUtils.registerBeanDefinition
				// 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));
		}
	}
TAG1 delegate.parseBeanDefinitionElement(ele)

BeanDefinitionParserDelegate.parseBeanDefinitionElement(Element ele)

	public BeanDefinitionHolder parseBeanDefinitionElement(Element ele) {
		return parseBeanDefinitionElement(ele, null);
	}
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean) {
     //解析bean的id和name属性
		String id = ele.getAttribute(ID_ATTRIBUTE);
		String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);

     	//解析name属性,用分隔符分离,用于解析如bean="a,b,c"多个别名定义的这种方式
		List<String> aliases = new ArrayList<>();
		if (StringUtils.hasLength(nameAttr)) {
			String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
			aliases.addAll(Arrays.asList(nameArr));
		}

		String beanName = id;
		if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
			beanName = aliases.remove(0);
			if (logger.isTraceEnabled()) {
				logger.trace("No XML 'id' specified - using '" + beanName +
						"' as bean name and " + aliases + " as aliases");
			}
		}

		if (containingBean == null) {
			checkNameUniqueness(beanName, aliases, ele);
		}

//TAG1.1 
     //解析bean(bean的大部分属性的解析过程)
		AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
		if (beanDefinition != null) {
			//省略
			}
			String[] aliasesArray = StringUtils.toStringArray(aliases);
               //将解析到的beandefinition封装到holder对象里:beandefinition、beanname、alias
			return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
		}

		return null;
	}
TAG1.1

BeanDefinitionParserDelegate

该方法创建GenericBeanDefinitio对象,并从ele节点中,分别解析出beandefinition的相关属性,并设置

	//解析bean标签的各种属性和子元素
	public AbstractBeanDefinition parseBeanDefinitionElement(
			Element ele, String beanName, @Nullable BeanDefinition containingBean) {

		this.parseState.push(new BeanEntry(beanName));

    	//ele节点的class名
		String className = null;
		if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
			className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
		}
    //ele节点的parent
		String parent = null;
		if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
			parent = ele.getAttribute(PARENT_ATTRIBUTE);
		}

		try {
               //用bean的class类型和父类,来创建GenericBeanDefinitio对象,spring用它扩展
			AbstractBeanDefinition bd = createBeanDefinition(className, parent);

               //解析bean标签的属性,解析结果设置到beandefinition中(解析属性核心方法)
			parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
			bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));

               /**解析xml中的meta标签,起到标记一个bean的作用 */
			parseMetaElements(ele, bd);
               
               //解析lookup-method、replace-method两种子标签(methodOverrides包装两个标签的所有属性)
               /**lookup-method:配置bean时,用来配置bean内的方法,设定返回的类为哪个实例
               */
			parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
               //解析replace——method标签
			parseReplacedMethodSubElements(ele, bd.getMethodOverrides());

               //解析构造函数子标签(constructor-arg)
			parseConstructorArgElements(ele, bd);
               //解析property子标签
			parsePropertyElements(ele, bd);
               //解析bean中的限定符标签
			parseQualifierElements(ele, bd);

			bd.setResource(this.readerContext.getResource());
			bd.setSource(extractSource(ele));

			return bd;
		}
	
		finally {
			this.parseState.pop();
		}

		return null;
	}

对创建的GeniricBeanDefinition对象,解析出的属性并设置如下:

image-20220319014359438

TAG2 delegate.decorateBeanDefinitionIfRequired(ele, bdHolder)

然后,返回DefaultBeanDefinitionDocumentReader.processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate)

protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
  //TAG1 
		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
		if (bdHolder != null) {
      //TAG2 
			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
			try {
				// Register the final decorated instance.
				BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
			}

BeanDefinitionParserDelegate.decorateBeanDefinitionIfRequired(Element ele, BeanDefinitionHolder originalDef)

	//装饰beandefinition其他功能
	public BeanDefinitionHolder decorateBeanDefinitionIfRequired(Element ele, BeanDefinitionHolder originalDef) {
		return decorateBeanDefinitionIfRequired(ele, originalDef, null);
	}

	//当有适用的,用namespace handler来装饰一个beandefinition
	public BeanDefinitionHolder decorateBeanDefinitionIfRequired(
			Element ele, BeanDefinitionHolder originalDef, @Nullable BeanDefinition containingBd) {

		BeanDefinitionHolder finalDefinition = originalDef;

		// Decorate based on custom attributes first.
          //对beandefinition装饰自定义的属性
		NamedNodeMap attributes = ele.getAttributes();
		for (int i = 0; i < attributes.getLength(); i++) {
      //获取特殊属性,对应的node节点
			Node node = attributes.item(i); //类似于bean标签中的p:username="paul"
      //根据node,装饰beandefinition
			finalDefinition = decorateIfRequired(node, finalDefinition, containingBd);
		}

		// Decorate based on custom nested elements.
          //通过嵌套子标签装饰
		NodeList children = ele.getChildNodes();
		for (int i = 0; i < children.getLength(); i++) {
      //获取嵌套子标签对应的节点
			Node node = children.item(i);
			if (node.getNodeType() == Node.ELEMENT_NODE) {
				finalDefinition = decorateIfRequired(node, finalDefinition, containingBd);
			}
		}
		return finalDefinition;
	}

对于默认bean标签下,解析出的beandefinition,需要判断是否有必要进行装饰处理。对于beandefinition中,有特殊属性、嵌套子标签的,需要将对应的这些节点node,装饰入beandefinitionHolder中。

	
	public BeanDefinitionHolder decorateIfRequired(
			Node node, BeanDefinitionHolder originalDef, @Nullable BeanDefinition containingBd) {
		//根据node获取namespaceURI
		String namespaceUri = getNamespaceURI(node);
          //当不是默认namespaceuri时(bean的URI)
		if (namespaceUri != null && !isDefaultNamespace(namespaceUri)) {
               
   //通过namespaceuri,拿到handlermappings,即namespaceuri和NamespaceHandler的映射关系对,获取namespaceHandler
               //详细见2.16 spring.handlers标签解析的原理
			NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
			if (handler != null) {
                    // 装饰beandefinition对象(该装饰器模式在自定义标签解析,使用到)
				BeanDefinitionHolder decorated =
						handler.decorate(node, originalDef, new ParserContext(this.readerContext, this, containingBd));
				if (decorated != null) {
					return decorated;
				}
			}
			else if (namespaceUri.startsWith("http://www.springframework.org/schema/")) {
				error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", node);
			}
			else {
				// A custom namespace, not to be handled by Spring - maybe "xml:...".
				if (logger.isDebugEnabled()) {
					logger.debug("No Spring NamespaceHandler found for XML schema namespace [" + namespaceUri + "]");
				}
			}
		}
		return originalDef;
	}
TAG3 readerUtils.registerBeanDefinition

然后,跳回返回DefaultBeanDefinitionDocumentReader.processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate)

protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
  //TAG1
		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
		if (bdHolder != null) {
      //TAG2
			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
			try {
//TAG3 readerUtils.registerBeanDefinition
				//注册最终装饰过的beandefinition对象
				BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
			}

BeanDefinitionReaderUtils.registerBeanDefinition(BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)

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

		// Register bean definition under primary name.
		String beanName = definitionHolder.getBeanName();
          //注册beanName、beandefinition到registry的核心方法
		registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());

		// Register aliases for bean name, if any.
          //注册beanName配置的别名,通过别名拿到beanname,然后再获取bean对象
		String[] aliases = definitionHolder.getAliases();
		if (aliases != null) {
			for (String alias : aliases) {
				registry.registerAlias(beanName, alias);
			}
		}
	}

DefaultListableBeanFactory.registerBeanDefinition(String beanName, BeanDefinition beanDefinition)

	public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
			throws BeanDefinitionStoreException {
          
          	else {
				// Still in startup registration phase
                    //beanDefinitionMap为核心容器,缓存beandefinition到map中
				this.beanDefinitionMap.put(beanName, beanDefinition);
                    //beanName核心容器,beanname缓存到其中,bean实例化时会使用到
				this.beanDefinitionNames.add(beanName);
				removeManualSingletonName(beanName);
			}
3.3.1.2.2 自定义标签解析

BeanDefinitionParserDelegate.parseCustomElement()解析自定义标签

	public BeanDefinition parseCustomElement(Element ele) {
		return parseCustomElement(ele, null);
	}

	//详细解析过程见2.16 spring.handlers解析标签的原理
	public BeanDefinition parseCustomElement(Element ele, @Nullable BeanDefinition containingBd) {
		String namespaceUri = getNamespaceURI(ele);
		if (namespaceUri == null) {
			return null;
		}
    
//TAG1 resolver.rosolve(namespaceUri)
          //通过xm文件,获取spring.handlers文件中namespaceUri对应标签的实现类handler
		NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
		if (handler == null) {
			error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele);
			return null;
		}
    
//TAG2 handler.parse()
          //调用对应的handler接口的parse核心方法,解析标签
		return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
	}
TAG1 resolver.rosolve(namespaceUri)

DefaultNamespaceHandlerResolver.resolve(String namespaceUri)

	public NamespaceHandler resolve(String namespaceUri) {
          //handlerMappings缓存namespaceuri和namespaceHandler的映射关系
		Map<String, Object> handlerMappings = getHandlerMappings();
		Object handlerOrClassName = handlerMappings.get(namespaceUri);
		if (handlerOrClassName == null) {
			return null;
		}
    //如果handlerMappings获取的是namespaceHandler
		else if (handlerOrClassName instanceof NamespaceHandler) {
			return (NamespaceHandler) handlerOrClassName;
		}
    //如果handlerMappings获取到handler的classname
		else {
			String className = (String) handlerOrClassName;
			try {
        	//通过创建handler的class对象,再实例化创建handler
				Class<?> handlerClass = ClassUtils.forName(className, this.classLoader);
				if (!NamespaceHandler.class.isAssignableFrom(handlerClass)) {
					throw new FatalBeanException("Class [" + className + "] for namespace [" + namespaceUri +
							"] does not implement the [" + NamespaceHandler.class.getName() + "] interface");
				}
        //实例化
				NamespaceHandler namespaceHandler = (NamespaceHandler) BeanUtils.instantiateClass(handlerClass);
        
        //执行handler的init初始化
				namespaceHandler.init();
                    //注册解析的handler对象,建立标签对应的namespaceuri和对应的处理类namespaceHandler的映射关系
				handlerMappings.put(namespaceUri, namespaceHandler);
				return namespaceHandler;
			}

DefaultNamespaceHandlerResolver.resolve(String namespaceUri)方法内,主要是从handlerMappings中,通过namespaceUri获取namespaceHandler对象;如果获取的是handler的classname,通过创建Class类,再分别实例化、初始化,并设置入handlerMappings内。

然后,分析handlerMappings内的namespaceUri和namespaceHandler的对应关系,是怎么在spring中设置的。

自定义标签,需要配置hadlers映射配置文件、xsd大纲描述文件、shema大纲文件

以内置的context标签为例,入下

image-20220319153656121

//需要实现NamespaceHandlerSupport接口,并override init()方法
public class ContextNamespaceHandler extends NamespaceHandlerSupport {

     //该方法,需要用registerBeanDefinitionParser注册标签对应的beanDefinitionParser解析类,用来解析标签内的属性到beandefinition中
	@Override
	public void init() {
		registerBeanDefinitionParser("property-placeholder", new PropertyPlaceholderBeanDefinitionParser());
		registerBeanDefinitionParser("property-override", new PropertyOverrideBeanDefinitionParser());
		registerBeanDefinitionParser("annotation-config", new AnnotationConfigBeanDefinitionParser());
		registerBeanDefinitionParser("component-scan", new ComponentScanBeanDefinitionParser());
		registerBeanDefinitionParser("load-time-weaver", new LoadTimeWeaverBeanDefinitionParser());
		registerBeanDefinitionParser("spring-configured", new SpringConfiguredBeanDefinitionParser());
		registerBeanDefinitionParser("mbean-export", new MBeanExportBeanDefinitionParser());
		registerBeanDefinitionParser("mbean-server", new MBeanServerBeanDefinitionParser());
	}

}
TAG2 handler.parse()
//所有的标签和包的解析类,都要实现该接口
public interface BeanDefinitionParser {

	//解析特定的标签,并注册生成的beandefinition到registry中
	@Nullable
	BeanDefinition parse(Element element, ParserContext parserContext);

}

以context:component-scan/标签为例,分析标签解析过程(xml中配置扫描的包basepackage位置,然后去扫描项目中的@component,@service等注解的bean

从ComponentScanBeanDefinitionParser.parse(Element element, ParserContext parserContext)

	public BeanDefinition parse(Element element, ParserContext parserContext) {
          //解析besepacket属性
		String basePackage = element.getAttribute(BASE_PACKAGE_ATTRIBUTE);
		basePackage = parserContext.getReaderContext().getEnvironment().resolvePlaceholders(basePackage);
          //解析用,分割的多个basePacket属性
		String[] basePackages = StringUtils.tokenizeToStringArray(basePackage,
				ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);

		// Actually scan for bean definitions and register them.
    
//TAG2.1 configureScanner(parserContext, element)
          //创建注解扫描器
		ClassPathBeanDefinitionScanner scanner = configureScanner(parserContext, element);
//TAG2.2 scanner.doScan(basePackages)
          //扫描besepackages包
		Set<BeanDefinitionHolder> beanDefinitions = scanner.doScan(basePackages);
          /**注册component
          beanPostProcessor接口的实现类,注册的方法点
          */
//TAG2.3 registerComponents
		registerComponents(parserContext.getReaderContext(), beanDefinitions, element);

		return null;
	}
TAG2.1 configureScanner(parserContext, element)
protected ClassPathBeanDefinitionScanner configureScanner(ParserContext parserContext, Element element) {
		boolean useDefaultFilters = true;
     //扫描USE_DEFAULT_FILTERS属性:包括@service,@component等注解
		if (element.hasAttribute(USE_DEFAULT_FILTERS_ATTRIBUTE)) {
			useDefaultFilters = Boolean.parseBoolean(element.getAttribute(USE_DEFAULT_FILTERS_ATTRIBUTE));
		}

		// Delegate bean definition registration to scanner class.
     //创建扫描器:defaultFilter为默认的@component,和继承了@component的子注解,如@service等
		ClassPathBeanDefinitionScanner scanner = createScanner(parserContext.getReaderContext(), useDefaultFilters);
		scanner.setBeanDefinitionDefaults(parserContext.getDelegate().getBeanDefinitionDefaults());
		scanner.setAutowireCandidatePatterns(parserContext.getDelegate().getAutowireCandidatePatterns());

		if (element.hasAttribute(RESOURCE_PATTERN_ATTRIBUTE)) {
			scanner.setResourcePattern(element.getAttribute(RESOURCE_PATTERN_ATTRIBUTE));
		}

		try {
			parseBeanNameGenerator(element, scanner);
		}
		catch (Exception ex) {
			parserContext.getReaderContext().error(ex.getMessage(), parserContext.extractSource(element), ex.getCause());
		}

		try {
			parseScope(element, scanner);
		}
		catch (Exception ex) {
			parserContext.getReaderContext().error(ex.getMessage(), parserContext.extractSource(element), ex.getCause());
		}
	//解析TypeFilters(配置扫描时的过滤类型,如这里过滤的是@component和@service等)
		parseTypeFilters(element, scanner, parserContext);
		return scanner;
	}

ClassPathBeanDefinitionScanner的构建(构造函数)

为给定的 bean 工厂创建一个新的 {@code ClassPathBeanDefinitionScanner},并在评估 bean 定义配置文件元数据时使用给定的 {@link Environment}。

	public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,
			Environment environment, @Nullable ResourceLoader resourceLoader) {

		Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
		this.registry = registry;

          //使用默认过滤器,扫描默认注解@service和@component
		if (useDefaultFilters) {
			registerDefaultFilters();
		}
		setEnvironment(environment);
		setResourceLoader(resourceLoader);
	}

ClassPathScanningCandidateComponentProvider.registerDefaultFilters()注册默认的注解类型过滤器

protected void registerDefaultFilters() {
     //添加(注册)@component注解,(@service继承了该注解)
		this.includeFilters.add(new AnnotationTypeFilter(Component.class));
		ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader();
TAG2.2 scanner.doScan(basePackages)

然后返回ComponentScanBeanDefinitionParser.parse

public BeanDefinition parse(Element element, ParserContext parserContext) {
   String basePackage = element.getAttribute(BASE_PACKAGE_ATTRIBUTE);
   basePackage = parserContext.getReaderContext().getEnvironment().resolvePlaceholders(basePackage);
   String[] basePackages = StringUtils.tokenizeToStringArray(basePackage,
         ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);

   // Actually scan for bean definitions and register them.
  //TAG2.1
   ClassPathBeanDefinitionScanner scanner = configureScanner(parserContext, element);
  //TAG2.2 scanner.doScan(basePackages)
   Set<BeanDefinitionHolder> beanDefinitions = scanner.doScan(basePackages);
  //TAG2.3 
   registerComponents(parserContext.getReaderContext(), beanDefinitions, element);

   return null;
}
//在指定的basepackages包中进行扫描,并返回注册的beandefinition
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
		Assert.notEmpty(basePackages, "At least one base package must be specified");
		Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
		for (String basePackage : basePackages) {
               
//TAG2.2.1 findCandidateComponents(basePackage)
               //核心方法:扫描有指定注解的class,并封装成beanDefinition对象
			Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
			for (BeanDefinition candidate : candidates) {
                    //封装class的元数据信息
				ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
				candidate.setScope(scopeMetadata.getScopeName());
				String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
                    //向beandefinition中设置自动装配属性值
				if (candidate instanceof AbstractBeanDefinition) {
//TAG2.2.2 postProcessBeanDefinition
					postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
				}
                    //支持@lazy,@dependon,@primary注解(设置部分注解支持)
				if (candidate instanceof AnnotatedBeanDefinition) {
					AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
				}
				if (checkCandidate(beanName, candidate)) {
					BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
					definitionHolder =
							AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
					beanDefinitions.add(definitionHolder);
                         //注册beandefinition
//TAG2.2.3 registerBeanDefinition(definitionHolder, this.registry)
					registerBeanDefinition(definitionHolder, this.registry);
				}
			}
		}
		return beanDefinitions;
	}
TAG2.2.1 findCandidateComponents(basePackage)

ClassPathScanningCandidateComponentProvider.findCandidateComponents()查找符合条件class的过程

	public Set<BeanDefinition> findCandidateComponents(String basePackage) {
		if (this.componentsIndex != null && indexSupportsIncludeFilters()) {
			return addCandidateComponentsFromIndex(this.componentsIndex, basePackage);
		}
		else {
               //扫描basepackage下符合条件的class(核心扫描方法)
			return scanCandidateComponents(basePackage);
		}
	}
	private Set<BeanDefinition> scanCandidateComponents(String basePackage) {
		Set<BeanDefinition> candidates = new LinkedHashSet<>();
		try {
               //模糊匹配包路径
			String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
					resolveBasePackage(basePackage) + '/' + this.resourcePattern;
               //递归查找class文件
			Resource[] resources = getResourcePatternResolver().getResources(packageSearchPath);
			boolean traceEnabled = logger.isTraceEnabled();
			boolean debugEnabled = logger.isDebugEnabled();
			for (Resource resource : resources) {
				if (resource.isReadable()) {
					try {
                              //类的元数据信息,用来包装类的基本信息
						MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(resource);
						if (isCandidateComponent(metadataReader)) {
							ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
							sbd.setResource(resource);
							sbd.setSource(resource);
                                   //过滤掉不符合条件的class,包括interface和抽象类
							if (isCandidateComponent(sbd)) {
								candidates.add(sbd);
							}
                                   return candidates;
                              }
TAG2.2.2 postProcessBeanDefinition

返回doScan的postProcessBeanDefinition,继续执行

ClassPathBeanDefinitionScanner.postProcessBeanDefinition

作用:除了通过扫描component class得到的内容外,将更多的settings应用到给定的beandefinition

	protected void postProcessBeanDefinition(AbstractBeanDefinition beanDefinition, String beanName) {
		beanDefinition.applyDefaults(this.beanDefinitionDefaults);
          //
		if (this.autowireCandidatePatterns != null) {
			beanDefinition.setAutowireCandidate(PatternMatchUtils.simpleMatch(this.autowireCandidatePatterns, beanName));
		}
	}
TAG2.2.3 registerBeanDefinition(definitionHolder, this.registry)

然后,执行doscan的注册方法registerBeanDefinition(definitionHolder, this.registry);

TAG2.3 registerComponents

之后,回到ComponentScanBeanDefinitionParser.parse

	public BeanDefinition parse(Element element, ParserContext parserContext) {
		String basePackage = element.getAttribute(BASE_PACKAGE_ATTRIBUTE);
		basePackage = parserContext.getReaderContext().getEnvironment().resolvePlaceholders(basePackage);
		String[] basePackages = StringUtils.tokenizeToStringArray(basePackage,
				ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);

		// Actually scan for bean definitions and register them.
    //TAG2.1
		ClassPathBeanDefinitionScanner scanner = configureScanner(parserContext, element);
    //TAG2.2
		Set<BeanDefinitionHolder> beanDefinitions = scanner.doScan(basePackages);
          //注册三大核心组件
    //TAG2.3
		registerComponents(parserContext.getReaderContext(), beanDefinitions, element);

		return null;
	}

ComponentScanBeanDefinitionParser.registerComponents()注册核心三大组件

	protected void registerComponents(
			XmlReaderContext readerContext, Set<BeanDefinitionHolder> beanDefinitions, Element element) {

		Object source = readerContext.extractSource(element);
		CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), source);

		for (BeanDefinitionHolder beanDefHolder : beanDefinitions) {
			compositeDef.addNestedComponent(new BeanComponentDefinition(beanDefHolder));
		}

		// Register annotation config processors, if necessary.
		boolean annotationConfig = true;
		if (element.hasAttribute(ANNOTATION_CONFIG_ATTRIBUTE)) {
			annotationConfig = Boolean.parseBoolean(element.getAttribute(ANNOTATION_CONFIG_ATTRIBUTE));
		}
		if (annotationConfig) {
			Set<BeanDefinitionHolder> processorDefinitions =
                    
                    /**核心后置处理组件,埋点设计
                    注册几个重要的beanPostProcessor接口的实现类:
                    AutowiredAnnotationBeanPostProcessor
                    ConfigurationClassPostProcessor
                    CommonAnnotationBeanPostProcessor
                    */
//TAG2.3.1 AnnotationConfigUtils.registerAnnotationConfigProcessors
					AnnotationConfigUtils.registerAnnotationConfigProcessors(readerContext.getRegistry(), source);
			for (BeanDefinitionHolder processorDefinition : processorDefinitions) {
				compositeDef.addNestedComponent(new BeanComponentDefinition(processorDefinition));
			}
		}

		readerContext.fireComponentRegistered(compositeDef);
	}
TAG2.3.1 AnnotationConfigUtils.registerAnnotationConfigProcessors

这里,完成对spring三大后置处理器的注册

	//在给定的registry中,注册所有相关的注释后处理器(AnnotationPostProcessors)
	public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
			BeanDefinitionRegistry registry, @Nullable Object source) {

		DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
		if (beanFactory != null) {
			if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
				beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
			}
			if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
				beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
			}
		}

		Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);
	//注册ConfigurationClassPostProcessor类的beandefinition
          //对@bean,@componentscan,@import的注解的解析
		if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
		}
	//注册autowiwiredAnnotationBeanPostProcessor类的beandefinition
          //完成@Autowired依赖注入的处理器
		if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
		}
	//注册CommonAnnotationBeanPostProcessor类的beandefinition
          //@post,@primary,@resource注解的实现,都在这个postProcessor实现类
		// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
		if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
		if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition();
			try {
				def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
						AnnotationConfigUtils.class.getClassLoader()));
			}
			catch (ClassNotFoundException ex) {
				throw new IllegalStateException(
						"Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
			}
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
		}

		if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
		}

		return beanDefs;
	}

后置处理器的注册,[详细看](#3.3.3 后置处理器的注册与实例化时机)

3.3.1.3 注解扫描

构造函数,注解扫描的入口

	public AnnotationConfigApplicationContext(String... basePackages) {
//TAG1 
		//完成三大组件注册、过滤器scanner设置
          this();
          //包扫描,注册beandefinition
//TAG2 scan(basePackages)
		scan(basePackages);
          //覆盖refresh方法
//TAG3 refresh()
		refresh();
	}
public AnnotationConfigApplicationContext() {
//TAG1.1 
     //该类,完成三大beanPostProcessor组件的beandefinition的注册
		this.reader = new AnnotatedBeanDefinitionReader(this);
//TAG1.2
     //完成默认扫描器scanner的注册:coponentScanner,NamespaceHandler的注册
		this.scanner = new ClassPathBeanDefinitionScanner(this);
	}
TAG1.1

AnnotatedBeanDefinitionReader初始化,构造函数中完成对三大组件的注册

	public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
		Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
		Assert.notNull(environment, "Environment must not be null");
		this.registry = registry;
		this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
          //同xml中,对三大组件的注册
    //同TAG2.3.1
		AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
	}
TAG1.2

ClassPathBeanDefinitionScanner扫描器,负责注册默认filter和namespaceUri

	public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,
			Environment environment, @Nullable ResourceLoader resourceLoader) {

		Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
		this.registry = registry;
		
          //默认过滤器,扫描默认注解@service和@component等。同xml中
		if (useDefaultFilters) {
			registerDefaultFilters();
		}
		setEnvironment(environment);
		setResourceLoader(resourceLoader);
	}
TAG2

scan————ClassPathBeanDefinitionScanner.scan(String... basePackages)

	public int scan(String... basePackages) {
		int beanCountAtScanStart = this.registry.getBeanDefinitionCount();

          //执行包扫描
		doScan(basePackages);

		// Register annotation config processors, if necessary.
		if (this.includeAnnotationConfig) {
     	//同默认bean标签解析TAG2.3.1
			AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
		}

		return (this.registry.getBeanDefinitionCount() - beanCountAtScanStart);
	}
TAG3 refresh

AbstractApplicationContext.refresh()容器上下文刷新, 同xml配置解析加载类似

	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
      
      // Prepare the bean factory for use in this context.
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
				initMessageSource();

				// Initialize event multicaster for this context.
				initApplicationEventMulticaster();

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

				// Check for listener beans and register them.
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
				finishRefresh();
			}
	protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
    //TAG3.1 refreshBeanFactory
		refreshBeanFactory();
		return getBeanFactory();
	}
TAG3.1 refreshBeanFactory

refreshBeanFactory的实现,xml和注解,用不同的类实现。注解用后者

注解扫描重写GenericApplicationContext.refreshBeanFactory()方法(没有重要实现);xml配置解析重写的是:AbstractRefreshableApplicationContext.refreshBeanFactory()方法(核心实现就在此);

image-20220320224022614

	@Override
	protected final void refreshBeanFactory() throws IllegalStateException {
		if (!this.refreshed.compareAndSet(false, true)) {
			throw new IllegalStateException(
					"GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
		}
		this.beanFactory.setSerializationId(getId());
	}

refresh()容器刷新的后续步骤,两种以上两种容器加载方式都相同。

posted @ 2023-03-10 17:07  LeasonXue  阅读(58)  评论(0编辑  收藏  举报