一起学SF框架系列5.8-模块Beans-注解bean解析2-解析配置annotation-config

本文主要讲述Spring是如何解析“annotation-config”,实际是加载注解对应解析器。

解析内容

1、解析的元素是:

<context:annotation-config/>

2、加载注解对应的解析器。

加载解析器

AnnotationConfigBeanDefinitionParser.parse(Element element, ParserContext parserContext)

此处element即为“context:annotation-config”。

	public BeanDefinition parse(Element element, ParserContext parserContext) {
		Object source = parserContext.extractSource(element);

		// 获取所有处理注解类的BeanPostProcessors(BeanPostProcessor本身也是bean) 注1
		Set<BeanDefinitionHolder> processorDefinitions =
				AnnotationConfigUtils.registerAnnotationConfigProcessors(parserContext.getRegistry(), source);

		// 生成关于元素(context:annotation-config)的组合组件(Component即bean),放到到解析容器待处理队列containingComponents中
		CompositeComponentDefinition compDefinition = new CompositeComponentDefinition(element.getTagName(), source);
		parserContext.pushContainingComponent(compDefinition);

		// 把注解BeanPostProcessor的BeanDefinition转换成ComponentDefinition,注册到解析容器的containingComponents的嵌套组件中
		for (BeanDefinitionHolder processorDefinition : processorDefinitions) {
			parserContext.registerComponent(new BeanComponentDefinition(processorDefinition));
		}

		// 触发组件注册事件
		parserContext.popAndRegisterContainingComponent();

		return null;
	}

注1:注解类的BeanPostProcessors都是SF框架提供。

AnnotationConfigUtils.registerAnnotationConfigProcessors( BeanDefinitionRegistry registry, @Nullable Object source)

1、设置bean工厂用于注解处理的属性实例(包括:AnnotationAwareOrderComparator、ContextAnnotationAutowireCandidateResolver、ContextAnnotationAutowireCandidateResolver)
2、把Spring用于解析注解的处理器bean(包括:ConfigurationClassPostProcessor、AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、InitDestroyAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor、EventListenerMethodProcessor、DefaultEventListenerFactory)的BeanDefinition形成集合返回

public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
        BeanDefinitionRegistry registry, Object source) {
 
    DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
    if (beanFactory != null) {
        if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
            // 设置dependencyComparator属性
            beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
        }
        if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
            // 设置autowireCandidateResolver属性(设置自动注入候选对象的解析器,用于判断BeanDefinition是否为候选对象)
            beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
        }
    }
 
    Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<BeanDefinitionHolder>(4);
 
    // 注册内部管理的用于处理@Configuration注解的后置处理器bean-ConfigurationClassPostProcessor
    if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
        RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
        def.setSource(source);
        // registerPostProcessor: 注册BeanDefinition到注册表中
        beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
    }
 
    // 注册内部管理的用于处理@Autowired、@Value、@Inject以及@Lookup注解的后置处理器bean-AutowiredAnnotationBeanPostProcessor
    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));
    }
 
    // 支持Jakarta注解,注册内部管理注解通用后置处理器bean-CommonAnnotationBeanPostProcessor
	if (jakartaAnnotationsPresent && !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));
	}
 
	    // 支持JSR-250注解(@PostConstruct,@PreDestroy)后置处理器的bean-InitDestroyAnnotationBeanPostProcessor
		if (jsr250Present && !registry.containsBeanDefinition(JSR250_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			try {
				RootBeanDefinition def = new RootBeanDefinition(InitDestroyAnnotationBeanPostProcessor.class);
				def.getPropertyValues().add("initAnnotationType", classLoader.loadClass("javax.annotation.PostConstruct"));
				def.getPropertyValues().add("destroyAnnotationType", classLoader.loadClass("javax.annotation.PreDestroy"));
				def.setSource(source);
				beanDefs.add(registerPostProcessor(registry, def, JSR250_ANNOTATION_PROCESSOR_BEAN_NAME));
			}
			catch (ClassNotFoundException ex) {
				// Failed to load javax variants of the annotation types -> ignore.
			}
		}
		
    // 注册内部管理的用于处理JPA注解的后置处理器bean-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));
    }
 
    // 注册内部管理的用于处理@EventListener注解的后置处理器bean
    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));
    }
    // 注册内部管理用于生产ApplicationListener对象的EventListenerFactory对象
    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;
}
 
private static BeanDefinitionHolder registerPostProcessor(
        BeanDefinitionRegistry registry, RootBeanDefinition definition, String beanName) {
 
    // 设置role
    definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
    // 注册BeanDefinition
    registry.registerBeanDefinition(beanName, definition);
    // 封装成BeanDefinitionHolder并返回
    return new BeanDefinitionHolder(definition, beanName);
}

你可能感兴趣的:(Spring学习系列,spring,java,开发语言)