spring 扫描包 不起作用

问题

spring中配置了包路径,但不扫描包,上网搜索后发现,eclipse导出包时勾选add directory entry就ok了。我的疑问是add directory entry作用是什么?spring扫包是什么原理,怎么会跟add directory entry有关系?

add directory entry作用

我们先来看一下add directory entry的作用。

工程目录
这里写图片描述

eclipse 导出包 勾选 add directory entry
这里写图片描述

eclipse 导出包 不勾选 add directory entry
这里写图片描述

使用jar命令查看不同
这里写图片描述

可以清晰的看到,添加了directory entry 的有文件夹信息;没有添加directory entry的没有文件夹信息。

spring扫包原理

ContextNamespaceHandler入手跟踪spring源码获知,spring通过Classloader.getResources(String path)获取资源

PathMatchingResourcePatternResolver.java

protected Set<Resource> doFindAllClassPathResources(String path) throws IOException {
        Set<Resource> result = new LinkedHashSet<Resource>(16);
        ClassLoader cl = getClassLoader();
        //使用java.lang.ClassLoader获取资源
        Enumeration<URL> resourceUrls = (cl != null ? cl.getResources(path) : ClassLoader.getSystemResources(path));
        while (resourceUrls.hasMoreElements()) {
            URL url = resourceUrls.nextElement();
            result.add(convertClassLoaderURL(url));
        }
        if ("".equals(path)) {
            // The above result is likely to be incomplete, i.e. only containing file system references.
            // We need to have pointers to each of the jar files on the classpath as well...
            addAllClassLoaderJarRoots(cl, result);
        }
        return result;
    }

这里模拟spring获取包代码,将导出的包加入到另外一个工程类路径下,获取包信息;添加没有文件夹信息的包后,url始终为空!添加有文件夹信息的包后,就可以获取到包资源了。

这里写图片描述

URL url = TestDirectoryEntry.class.getClassLoader().getResource("a");
System.out.println(url);

总结

add directory entry,jar包包含文件夹信息,可以根据包名获取资源信息;

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值