spring classpath 理解

8月 21, 2014 |

网上有很多分析这个主题的文章,要么很啰嗦,要么很表面。其实spring解析classpath的逻辑在
spring-core-3.1.1.RELEASE.jar包的
Resource[] org.springframework.core.io.support.PathMatchingResourcePatternResolver.getResources(String locationPattern) throws IOException
方法中实现的,查看source code, 一目了然。
当然在spring-framework-reference 的6.7 Application contexts and Resource paths 下的
Wildcards in application context constructor resource paths 小节也有详细的介绍,
归纳如下:
面对classpath*:mapper/**/*Mapper.xml 这样的路径, 先调用classloader.getResource("mapper") 查找class loader能找到的所有路径(包括在jar文件中的),即返回一个Resource数组,代
表包含要查找的资源的可能路径, 然后在这些路径中查找满足“**/*Mapper.xml”模式的资源返回。(顺便说一下"**"表示零个或者多个目录, "*"表示零个或者多个字符, 见
org.springframework.util.AntPathMatcher 的javadoc)
面对classpath:mapper/**/*Mapper.xml 这样的路径, 先调用classloader.getResource("mapper") 查找class loader能找到的第一个路径(通常是在文件系统中而不是jar 中),在这个路径中查找满足“**/*Mapper.xml”模式的资源返回。

spring 的官方文档还提到了一个注意事项:classpath*:**/*Mapper.xml 这种模式只会搜索文件系统,不会搜索jar中的资源,因为非通配符的前面部分为"", classloader.getResource("") 的实现就是只会搜索文件系统。希望我的解释能让你豁然开朗。

Posted in: spring practise | Tags: ,

Comments are closed.