Spring5 新特性-spring.components

举报
龙哥手记 发表于 2022/11/22 19:36:32 2022/11/22
【摘要】 《读尽源码 第四十篇》

解析

  • 相关类: org.springframework.context.index.CandidateComponentsIndexLoader
  • 测试用例: org.springframework.context.annotation.ClassPathScanningCandidateComponentProviderTests.defaultsWithIndex,org.springframework.context.index.CandidateComponentsIndexLoaderTests
  • CandidateComponentsIndexLoader是怎么找出来的,全文搜索spring.components

使用介绍

  • 下面是从resources/example/scannable/spring.components测试用例中复制过来的,从中可以发现等号左侧放的是我们写的组件,等号右边是属于什么组件
example.scannable.AutowiredQualifierFooService=example.scannable.FooService
example.scannable.DefaultNamedComponent=org.springframework.stereotype.Component
example.scannable.NamedComponent=org.springframework.stereotype.Component
example.scannable.FooService=example.scannable.FooService
example.scannable.FooServiceImpl=org.springframework.stereotype.Component,example.scannable.FooService
example.scannable.ScopedProxyTestBean=example.scannable.FooService
example.scannable.StubFooDao=org.springframework.stereotype.Component
example.scannable.NamedStubDao=org.springframework.stereotype.Component
example.scannable.ServiceInvocationCounter=org.springframework.stereotype.Component
example.scannable.sub.BarComponent=org.springframework.stereotype.ComponentCopy to clipboardErrorCopied

debug

  • 入口 org.springframework.context.index.CandidateComponentsIndexLoader.loadIndex
    @Nullable
    public static CandidateComponentsIndex loadIndex(@Nullable ClassLoader classLoader) {
        ClassLoader classLoaderToUse = classLoader;
        if (classLoaderToUse == null) {
            classLoaderToUse = CandidateComponentsIndexLoader.class.getClassLoader();
        }
        return cache.computeIfAbsent(classLoaderToUse, CandidateComponentsIndexLoader::doLoadIndex);
    }
Copy to clipboardErrorCopied
    /**
     * 解析  META-INF/spring.components 文件
     * @param classLoader
     * @return
     */
    @Nullable
    private static CandidateComponentsIndex doLoadIndex(ClassLoader classLoader) {
        if (shouldIgnoreIndex) {
            return null;
        }

        try {
            Enumeration<URL> urls = classLoader.getResources(COMPONENTS_RESOURCE_LOCATION);
            if (!urls.hasMoreElements()) {
                return null;
            }
            List<Properties> result = new ArrayList<>();
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                // 读取META-INF/spring.components文件转换成map对象
                Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
                result.add(properties);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Loaded " + result.size() + "] index(es)");
            }
            int totalCount = result.stream().mapToInt(Properties::size).sum();
            // 查看CandidateComponentsIndex方法
            return (totalCount > 0 ? new CandidateComponentsIndex(result) : null);
        }
        catch (IOException ex) {
            throw new IllegalStateException("Unable to load indexes from location [" +
                    COMPONENTS_RESOURCE_LOCATION + "]", ex);
        }
    }
Copy to clipboardErrorCopied
  CandidateComponentsIndex(List<Properties> content) {
        this.index = parseIndex(content);
    }

    /**
     * 解析  MATE-INF\spring.components 转换成 map
     *
     * @param content
     * @return
     */
    private static MultiValueMap<String, Entry> parseIndex(List<Properties> content) {
        MultiValueMap<String, Entry> index = new LinkedMultiValueMap<>();
        for (Properties entry : content) {
            entry.forEach((type, values) -> {
                String[] stereotypes = ((String) values).split(",");
                for (String stereotype : stereotypes) {
                    index.add(stereotype, new Entry((String) type));
                }
            });
        }
        return index;
    }Copy to clipboardErrorCopied

image-20200115105941265

  • 该类给org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.findCandidateComponents提供了帮助
    public Set<BeanDefinition> findCandidateComponents(String basePackage) {
        // 扫描
        /**
         * if 测试用例: {@link org.springframework.context.annotation.ClassPathScanningCandidateComponentProviderTests#defaultsWithIndex()}
         * 解析 spring.components文件
         */
        if (this.componentsIndex != null && indexSupportsIncludeFilters()) {
            return addCandidateComponentsFromIndex(this.componentsIndex, basePackage);
        }
        else {
            return scanCandidateComponents(basePackage);
        }
    }
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。