spring 扫描包 不起作用

    xiaoxiao2026-03-03  10

    问题

    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包包含文件夹信息,可以根据包名获取资源信息;

    转载请注明原文地址: https://ju.6miu.com/read-1307570.html
    最新回复(0)