关于后端:Spring-源码解析九默认的注解处理器

47次阅读

共计 20108 个字符,预计需要花费 51 分钟才能阅读完成。

Spring 源码解析九:默认的注解处理器

在 Spring 源码解析五:Bean 的配置、定义、注册 中,有一些默认的注解处理器还未解析

  • ConfigurationClassPostProcessor
  • AutowiredAnnotationBeanPostProcessor
  • CommonAnnotationBeanPostProcessor
  • PersistenceAnnotationBeanPostProcessor
  • EventListenerMethodProcessor
  • DefaultEventListenerFactory

1. ConfigurationClassPostProcessor

ConfigurationClassPostProcessor
的次要性能是解决 @Configuration

public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPostProcessor,
        PriorityOrdered, ResourceLoaderAware, ApplicationStartupAware, BeanClassLoaderAware, EnvironmentAware {
    // 后置解决 registry
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
        // ... 代码省略

        // 解决配置类 bean 定义
        processConfigBeanDefinitions(registry);
    }

    // 后置解决 registry
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
        // ... 代码省略

        // 解决配置类 bean 定义
        processConfigBeanDefinitions((BeanDefinitionRegistry) beanFactory);

        // 应用 ConfigurationClassEnhancer 对 @Configuration 的 class 进行 cglib 加强
        enhanceConfigurationClasses(beanFactory);

        // ... 代码省略
    }
}
public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPostProcessor,
        PriorityOrdered, ResourceLoaderAware, ApplicationStartupAware, BeanClassLoaderAware, EnvironmentAware {
    // 解决配置类 bean 定义
    public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
        // 配置类汇合
        List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
        // 所有 bean 的名字
        String[] candidateNames = registry.getBeanDefinitionNames();

        // 遍历
        for (String beanName : candidateNames) {
            // 获取 bean 定义
            BeanDefinition beanDef = registry.getBeanDefinition(beanName);

            // ... 代码省略

            // 如果是 @Configuration 标记的类,退出汇合
            if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
            }
        }

        // 没有 @Configuration 标记的类,返回
        if (configCandidates.isEmpty()) {return;}

        // ... 代码省略

        // 获取 @Configuration 类解析器
        ConfigurationClassParser parser = new ConfigurationClassParser(
                this.metadataReaderFactory, this.problemReporter, this.environment,
                this.resourceLoader, this.componentScanBeanNameGenerator, registry);

        // 待解析汇合
        Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
        // 已解析汇合
        Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
        do {
            // ... 代码省略

            // 解析配置类
            parser.parse(candidates);
            // 验证配置类
            parser.validate();

            // 获取所有的配置类,包含以前注册的
            Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
            // 移除已解析的
            configClasses.removeAll(alreadyParsed);

            if (this.reader == null) {
                // 应用 ConfigurationClassBeanDefinitionReader 创立配置类 bean 定义读取器
                this.reader = new ConfigurationClassBeanDefinitionReader(
                        registry, this.sourceExtractor, this.resourceLoader, this.environment,
                        this.importBeanNameGenerator, parser.getImportRegistry());
            }
            // 读取 bean 定义
            this.reader.loadBeanDefinitions(configClasses);
            // 增加到已解析
            alreadyParsed.addAll(configClasses);

            // ... 代码省略
        }
        while (!candidates.isEmpty());

        // ... 代码省略
    }
}

@Configuration 类的解决外围是 ConfigurationClassParser
实现的

class ConfigurationClassParser {public void parse(Set<BeanDefinitionHolder> configCandidates) {for (BeanDefinitionHolder holder : configCandidates) {BeanDefinition bd = holder.getBeanDefinition();
            try {
                // AnnotatedBeanDefinition 解决
                if (bd instanceof AnnotatedBeanDefinition) {parse1(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
                }
                // AbstractBeanDefinition+beanClass 解决
                else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {parse2(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());
                }
                // 默认解决
                else {parse3(bd.getBeanClassName(), holder.getBeanName());
                }
            }
            catch (BeanDefinitionStoreException ex) {// ... 代码省略}
            // ... 代码省略
        }

        // ... 代码省略
    }

    protected final void parse1(AnnotationMetadata metadata, String beanName) throws IOException {processConfigurationClass(new ConfigurationClass(metadata, beanName), DEFAULT_EXCLUSION_FILTER);
    }

    protected final void parse2(Class<?> clazz, String beanName) throws IOException {processConfigurationClass(new ConfigurationClass(clazz, beanName), DEFAULT_EXCLUSION_FILTER);
    }

    protected final void parse3(@Nullable String className, String beanName) throws IOException {MetadataReader reader = this.metadataReaderFactory.getMetadataReader(className);
        processConfigurationClass(new ConfigurationClass(reader, beanName), DEFAULT_EXCLUSION_FILTER);
    }
}
class ConfigurationClassParser {protected void processConfigurationClass(ConfigurationClass configClass, Predicate<String> filter) throws IOException {
        // ... 代码省略

        // 包裹成 SourceClass
        SourceClass sourceClass = asSourceClass(configClass, filter);
        // 遍历解决配置类,及其父类
        do {sourceClass = doProcessConfigurationClass(configClass, sourceClass, filter);
        }
        while (sourceClass != null);

        // ... 代码省略
    }

    // 解决配置类
    protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter)
            throws IOException {

        // 解决 @Component 注解
        if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
            // 遍历解决外部类(非动态外部类)processMemberClasses(configClass, sourceClass, filter);
        }

        // 解决 @PropertySource 注解,装载属性都 bean 中
        for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(sourceClass.getMetadata(), PropertySources.class,
                org.springframework.context.annotation.PropertySource.class)) {
            // 装载属性都 bean 中
            processPropertySource(propertySource);
        }

        // 解决 @ComponentScan 注解,扫描指定的包
        Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
        if (!componentScans.isEmpty() &&
                !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
            // 遍历扫描
            for (AnnotationAttributes componentScan : componentScans) {
                // 扫描到的 bean 定义
                Set<BeanDefinitionHolder> scannedBeanDefinitions =
                        this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
                // 遍历 bean 定义
                for (BeanDefinitionHolder holder : scannedBeanDefinitions) {BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
                    // 如果也标记有 @Configuration,持续解析
                    if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {parse(bdCand.getBeanClassName(), holder.getBeanName());
                    }
                }
            }
        }

        // 解决 @Import 注解
        processImports(configClass, sourceClass, getImports(sourceClass), filter, true);

        // 解决 @ImportResource 注解
        AnnotationAttributes importResource =
                AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
        if (importResource != null) {// ... 代码省略}

        // 解决类中标记为 @Bean 的办法
        Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
        for (MethodMetadata methodMetadata : beanMethods) {configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
        }

        // 如果类是接口,注入默认的办法
        processInterfaces(configClass, sourceClass);

        // 如果有父类,返回父类,持续遍历
        if (sourceClass.getMetadata().hasSuperClass()) {// ... 代码省略}

        // 没有父类,完结遍历
        return null;
    }
}

2. AutowiredAnnotationBeanPostProcessor

ConfigurationClassPostProcessor
的次要性能是解决 bean 的主动拆卸

public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationAwareBeanPostProcessor,
        MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
    // 默认解决 @Autowired、@Value、@Inject 三个注解
    public AutowiredAnnotationBeanPostProcessor() {this.autowiredAnnotationTypes.add(Autowired.class);
        this.autowiredAnnotationTypes.add(Value.class);
        try {this.autowiredAnnotationTypes.add((Class<? extends Annotation>)
                    ClassUtils.forName("javax.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));
        }
        catch (ClassNotFoundException ex) {// ... 代码省略}
    }

    // 解决属性注入
    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
        // 查找须要注入的元信息
        InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
        try {
            // 注入
            metadata.inject(bean, beanName, pvs);
        }
        catch (BeanCreationException ex) {// ... 代码省略}

        return pvs;
    }

    // 查找须要注入的元信息
    private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
        // 加锁的形式取出
        InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
        if (InjectionMetadata.needsRefresh(metadata, clazz)) {synchronized (this.injectionMetadataCache) {metadata = this.injectionMetadataCache.get(cacheKey);
                if (InjectionMetadata.needsRefresh(metadata, clazz)) {if (metadata != null) {metadata.clear(pvs);
                    }
                    // 构建元信息
                    metadata = buildAutowiringMetadata(clazz);
                    this.injectionMetadataCache.put(cacheKey, metadata);
                }
            }
        }
        return metadata;
    }
}
public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationAwareBeanPostProcessor,
        MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
    // 构建元信息
    private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
        // ... 代码省略

        // 注入元素汇合
        List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
        Class<?> targetClass = clazz;

        do {
            //  以后元素汇合
            final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();
            // 遍历本地属性
            ReflectionUtils.doWithLocalFields(targetClass, field -> {
                // 获取 @Autowired、@Value、@Inject 注解
                MergedAnnotation<?> ann = findAutowiredAnnotation(field);
                if (ann != null) {if (Modifier.isStatic(field.getModifiers())) {
                        // 动态属性不能注入
                        return;
                    }
                    // required 配置
                    boolean required = determineRequiredStatus(ann);
                    // 退出属性元素
                    currElements.add(new AutowiredFieldElement(field, required));
                }
            });

            // 遍历本地办法
            ReflectionUtils.doWithLocalMethods(targetClass, method -> {Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);

                // ... 代码省略

                // 获取 @Autowired、@Value、@Inject 注解
                MergedAnnotation<?> ann = findAutowiredAnnotation(bridgedMethod);
                if (ann != null) {if (Modifier.isStatic(method.getModifiers())) {
                        // 静态方法不能注入
                        return;
                    }

                    // required 配置
                    boolean required = determineRequiredStatus(ann);
                    PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                    // 退出办法元素
                    currElements.add(new AutowiredMethodElement(method, required, pd));
                }
            });

            // 增加进注入元素汇合
            elements.addAll(0, currElements);
            // 遍历父类
            targetClass = targetClass.getSuperclass();}
        while (targetClass != null && targetClass != Object.class);

        return InjectionMetadata.forElements(elements, clazz);
    }
}

属性的注入是 AutowiredFieldElement.inject 实现的,办法参数的注入是 AutowiredMethodElement.inject 实现的

private class AutowiredFieldElement extends InjectionMetadata.InjectedElement {
    @Override
    protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {Field field = (Field) this.member;
        Object value;
        if (this.cached) {
            // 先从缓存中获取 bean,其次从 registry 获取 bean
            value = resolvedCachedArgument(beanName, this.cachedFieldValue);
        }
        else {
            // 实例化一个 DependencyDescriptor 对象
            DependencyDescriptor desc = new DependencyDescriptor(field, this.required);

            // ... 代码省略

            try {
                // 从 registry 获取 bean
                value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
            }
            catch (BeansException ex) {// ... 代码省略}
            synchronized (this) {
                // ... 代码省略

                // 把 autowiredBeanNames 注册为 beanName 的依赖
                registerDependentBeans(beanName, autowiredBeanNames);

                // ... 代码省略
            }
        }
        // 把 bean 注入到属性中
        if (value != null) {ReflectionUtils.makeAccessible(field);
            field.set(bean, value);
        }
    }
}
private class AutowiredMethodElement extends InjectionMetadata.InjectedElement {
    @Override
    protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
        // ... 代码省略

        Method method = (Method) this.member;
        Object[] arguments;
        if (this.cached) {
            // 先从缓存中获取参数 bean 汇合,其次从 registry 获取参数 bean 汇合
            arguments = resolveCachedArguments(beanName);
        }
        else {
            // 参数个数
            int argumentCount = method.getParameterCount();
            // 参数汇合
            arguments = new Object[argumentCount];

            // ... 代码省略

            for (int i = 0; i < arguments.length; i++) {
                // 参数对象
                MethodParameter methodParam = new MethodParameter(method, i);

                // ... 代码省略

                try {
                    // 获取参数注入的 bean
                    Object arg = beanFactory.resolveDependency(currDesc, beanName, autowiredBeans, typeConverter);

                    // ... 代码省略

                    arguments[i] = arg;
                }
                catch (BeansException ex) {// ... 代码省略}
            }

            // ... 代码省略
        }
        // 把 bean 注入到参数中
        if (arguments != null) {
            try {ReflectionUtils.makeAccessible(method);
                method.invoke(bean, arguments);
            }
            catch (InvocationTargetException ex) {// ... 代码省略}
        }
    }
}

3. CommonAnnotationBeanPostProcessor

CommonAnnotationBeanPostProcessor
的次要性能是解决通用 java 注解javax.annotation.*

public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBeanPostProcessor
        implements InstantiationAwareBeanPostProcessor, BeanFactoryAware, Serializable {
    // 解决属性注入
    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
        // 查找须要注入的元信息
        InjectionMetadata metadata = findResourceMetadata(beanName, bean.getClass(), pvs);
        try {
            // 注入
            metadata.inject(bean, beanName, pvs);
        }
        catch (Throwable ex) {// ... 代码省略}
        return pvs;
    }

    // 查找须要注入的元信息
    private InjectionMetadata findResourceMetadata(String beanName, final Class<?> clazz, @Nullable PropertyValues pvs) {
        // 加锁的形式取出
        InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
        if (InjectionMetadata.needsRefresh(metadata, clazz)) {synchronized (this.injectionMetadataCache) {metadata = this.injectionMetadataCache.get(cacheKey);
                if (InjectionMetadata.needsRefresh(metadata, clazz)) {if (metadata != null) {metadata.clear(pvs);
                    }
                    // 构建元信息
                    metadata = buildResourceMetadata(clazz);
                    this.injectionMetadataCache.put(cacheKey, metadata);
                }
            }
        }
        return metadata;
    }
}
public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBeanPostProcessor
        implements InstantiationAwareBeanPostProcessor, BeanFactoryAware, Serializable {
    // 构建元信息
    private InjectionMetadata buildResourceMetadata(final Class<?> clazz) {
        // ... 代码省略

        // 注入元素汇合
        List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
        Class<?> targetClass = clazz;

        do {
            //  以后元素汇合
            final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();
            // 遍历本地属性
            ReflectionUtils.doWithLocalFields(targetClass, field -> {
                // @WebServiceRef 注解
                if (webServiceRefClass != null && field.isAnnotationPresent(webServiceRefClass)) {if (Modifier.isStatic(field.getModifiers())) {// 动态属性不能注入}
                    currElements.add(new WebServiceRefElement(field, field, null));
                }
                // @EJB 注解
                else if (ejbClass != null && field.isAnnotationPresent(ejbClass)) {if (Modifier.isStatic(field.getModifiers())) {// 动态属性不能注入}
                    currElements.add(new EjbRefElement(field, field, null));
                }
                // @Resource 注解
                else if (field.isAnnotationPresent(Resource.class)) {if (Modifier.isStatic(field.getModifiers())) {// 动态属性不能注入}
                    if (!this.ignoredResourceTypes.contains(field.getType().getName())) {currElements.add(new ResourceElement(field, field, null));
                    }
                }
            });

            // 遍历本地办法
            ReflectionUtils.doWithLocalMethods(targetClass, method -> {Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);

                // ... 代码省略

                // @WebServiceRef 注解
                if (webServiceRefClass != null && bridgedMethod.isAnnotationPresent(webServiceRefClass)) {if (Modifier.isStatic(method.getModifiers())) {// 静态方法不能注入}
                    PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                    currElements.add(new WebServiceRefElement(method, bridgedMethod, pd));
                }
                // @EJB 注解
                else if (ejbClass != null && bridgedMethod.isAnnotationPresent(ejbClass)) {if (Modifier.isStatic(method.getModifiers())) {// 静态方法不能注入}
                    PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                    currElements.add(new EjbRefElement(method, bridgedMethod, pd));
                }
                // @Resource 注解
                else if (bridgedMethod.isAnnotationPresent(Resource.class)) {if (Modifier.isStatic(method.getModifiers())) {// 静态方法不能注入}
                    if (!this.ignoredResourceTypes.contains(paramTypes[0].getName())) {PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                        currElements.add(new ResourceElement(method, bridgedMethod, pd));
                    }
                }
            });

            // 增加进注入元素汇合
            elements.addAll(0, currElements);
            // 遍历父类
            targetClass = targetClass.getSuperclass();}
        while (targetClass != null && targetClass != Object.class);

        return InjectionMetadata.forElements(elements, clazz);
    }
}

4. PersistenceAnnotationBeanPostProcessor

PersistenceAnnotationBeanPostProcessor
的次要性能是解决长久化 java 注解javax.persistence.*

public class PersistenceAnnotationBeanPostProcessor
        implements InstantiationAwareBeanPostProcessor, DestructionAwareBeanPostProcessor,
        MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware, Serializable {
    // 解决属性注入
    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
        // 查找须要注入的元信息
        InjectionMetadata metadata = findPersistenceMetadata(beanName, bean.getClass(), pvs);
        try {
            // 注入
            metadata.inject(bean, beanName, pvs);
        }
        catch (Throwable ex) {// ... 代码省略}
        return pvs;
    }

    // 查找须要注入的元信息
    private InjectionMetadata findPersistenceMetadata(String beanName, final Class<?> clazz, @Nullable PropertyValues pvs) {
        // 加锁的形式取出
        InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
        if (InjectionMetadata.needsRefresh(metadata, clazz)) {synchronized (this.injectionMetadataCache) {metadata = this.injectionMetadataCache.get(cacheKey);
                if (InjectionMetadata.needsRefresh(metadata, clazz)) {if (metadata != null) {metadata.clear(pvs);
                    }
                    // 构建元信息
                    this.injectionMetadataCache.put(cacheKey, metadata);
                }
            }
        }
        return metadata;
    }
}
public class PersistenceAnnotationBeanPostProcessor
        implements InstantiationAwareBeanPostProcessor, DestructionAwareBeanPostProcessor,
        MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware, Serializable {
    // 构建元信息
    private InjectionMetadata buildPersistenceMetadata(final Class<?> clazz) {
        // ... 代码省略

        // 注入元素汇合
        List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
        Class<?> targetClass = clazz;

        do {
            //  以后元素汇合
            final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();
            // 遍历本地属性
            ReflectionUtils.doWithLocalFields(targetClass, field -> {
                // 有 @PersistenceContext、@PersistenceUnit 注解
                if (field.isAnnotationPresent(PersistenceContext.class) ||
                        field.isAnnotationPresent(PersistenceUnit.class)) {if (Modifier.isStatic(field.getModifiers())) {// 动态属性不能注入}
                    currElements.add(new PersistenceElement(field, field, null));
                }
            });

            // 遍历本地办法
            ReflectionUtils.doWithLocalMethods(targetClass, method -> {Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);

                // ... 代码省略

                // 有 @PersistenceContext、@PersistenceUnit 注解
                if ((bridgedMethod.isAnnotationPresent(PersistenceContext.class) ||
                        bridgedMethod.isAnnotationPresent(PersistenceUnit.class)) &&
                        method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {if (Modifier.isStatic(method.getModifiers())) {// 静态方法不能注入}
                    PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                    currElements.add(new PersistenceElement(method, bridgedMethod, pd));
                }
            });

            // 增加进注入元素汇合
            elements.addAll(0, currElements);
            // 遍历父类
            targetClass = targetClass.getSuperclass();}
        while (targetClass != null && targetClass != Object.class);

        return InjectionMetadata.forElements(elements, clazz);
    }
}

5. EventListenerMethodProcessor

EventListenerMethodProcessor
的次要性能是处理事件监听@EventListener

public class EventListenerMethodProcessor
        implements SmartInitializingSingleton, ApplicationContextAware, BeanFactoryPostProcessor {
    // 单例 bean 初始化后
    @Override
    public void afterSingletonsInstantiated() {
        ConfigurableListableBeanFactory beanFactory = this.beanFactory;

        // 获取所有的 bean
        String[] beanNames = beanFactory.getBeanNamesForType(Object.class);
        for (String beanName : beanNames) {
            Class<?> type = null;
            try {
                // 获取 bean 类型
                type = AutoProxyUtils.determineTargetClass(beanFactory, beanName);
            }
            catch (Throwable ex) {// ... 代码省略}
            if (type != null) {
                // ... 代码省略

                try {
                    //  解决 bean
                    processBean(beanName, type);
                }
                catch (Throwable ex) {// ... 代码省略}
            }
        }
    }

    //  解决 bean
    private void processBean(final String beanName, final Class<?> targetType) {
        // 是以 org.springframework. 结尾的类或有 @EventListener 注解
        if (!this.nonAnnotatedClasses.contains(targetType) &&
                AnnotationUtils.isCandidateClass(targetType, EventListener.class) &&
                !isSpringContainerClass(targetType)) {

            Map<Method, EventListener> annotatedMethods = null;
            try {
                // 抉择有 @EventListener 注解的办法
                annotatedMethods = MethodIntrospector.selectMethods(targetType,
                        (MethodIntrospector.MetadataLookup<EventListener>) method ->
                                AnnotatedElementUtils.findMergedAnnotation(method, EventListener.class));
            }
            catch (Throwable ex) {// ... 代码省略}

            // 上下文对象
            ConfigurableApplicationContext context = this.applicationContext;
            // 监听器工厂
            List<EventListenerFactory> factories = this.eventListenerFactories;

            // 遍历办法
            for (Method method : annotatedMethods.keySet()) {
                // 遍历工厂
                for (EventListenerFactory factory : factories) {
                    // 如果工厂间接解析监听办法
                    if (factory.supportsMethod(method)) {
                        // 包装办法
                        Method methodToUse = AopUtils.selectInvocableMethod(method, context.getType(beanName));
                        // 封装为规范的监听器
                        ApplicationListener<?> applicationListener =
                                factory.createApplicationListener(beanName, targetType, methodToUse);

                        // ... 代码省略

                        // 增加进上下文
                        context.addApplicationListener(applicationListener);
                        break;
                    }
                }
            }
        }
    }
}

6. DefaultEventListenerFactory

DefaultEventListenerFactory
的次要性能是封装有 @EventListener 注解的办法为规范的监听器

public class DefaultEventListenerFactory implements EventListenerFactory, Ordered {
    @Override
    public ApplicationListener<?> createApplicationListener(String beanName, Class<?> type, Method method) {return new ApplicationListenerMethodAdapter(beanName, type, method);
    }
}

实质上就是用 ApplicationListenerMethodAdapter

public class ApplicationListenerMethodAdapter implements GenericApplicationListener {
    // 调用监听办法
    @Override
    public void onApplicationEvent(ApplicationEvent event) {processEvent(event);
    }

    // 处理事件
    public void processEvent(ApplicationEvent event) {
        // 获取调用办法的参数,如果有 payload,获取 payload,没有就是 event 自身
        Object[] args = resolveArguments(event);
        // 如果合乎 @EventListener 的 condition 设置,则触发
        if (shouldHandle(event, args)) {
            // 调用 method.invoke 获取后果
            Object result = doInvoke(args);
            if (result != null) {
                //  以此后果,持续派发其余事件
                handleResult(result);
            }
        }
    }
}

后续

更多博客,查看 https://github.com/senntyou/blogs

作者:深予之 (@senntyou)

版权申明:自在转载 - 非商用 - 非衍生 - 放弃署名(创意共享 3.0 许可证)

正文完
 0