spring中 base-package 属性指定要扫描的基础包。我们可以在配置中使用匹配符和占位符。
通配符说明:
- ? 匹配一个字符
- * 匹配空或匹配至少一个字符但不包含分割符(默认分割符为‘/’)
- ** 匹配空或匹配至少一个字符可以包含分割符(默认分割符为‘/’)
<!-- 完整的包 -->
<context:component-scan base-package="com.test" />
<!-- 使用通配符,只能匹配 com.a.test 无法匹配 com.a.b.test -->
<context:component-scan base-package="com.*.test" />
<!-- 使用通配符, 可以匹配 com.a.b.test 和com.a.test -->
<context:component-scan base-package="com.**.test" />
<!-- 使用占位符-->
<context:component-scan base-package="com.${test}.test" />
spring 源码分析 ClassPathScanningCandidateComponentProvider:
解析步骤:
- 解析占位符
- 将“.”替换为“/”
- 追加 “/**/*.class”
- 由ResourcePatternResolver接口(默认采用 PathMatchingResourcePatternResolver实现)加载资源
PathMatchingResourcePatternResolver#findPathMatchingResources 源码
解析步骤:
- 将locationPattern分割为两部分,第一部分(rootDirPath)不包含匹配符,第二部分(subPattern)包含匹配符
- 获取rootDirPath下的所有资源,并将资源相对路径与subPattern 匹配。
注:路径与subPattern 的匹配是有 AntPathMatcher 类来实现的
对AntPathMatcher的测试:
public static AntPathMatcher ant = new AntPathMatcher();
public static void main(String[] args) {
test("com*/test", "comaaaa/test"); // true
test("com*/test", "com/test"); // true
test("com**/test", "comaaaa/test"); // true
test("com**/test", "com/test"); // true
test("com**/test", "com/a/test"); // false
test("com/*/test", "com/test"); // false
test("com/*/test", "com/a/test"); // true
test("com/*/test", "com/a/b/test"); // false
test("com/**/test", "com/test"); // true
test("com/**/test", "com/a/test"); // true
test("com/**/test", "com/a/b/test");// true
}
public static void test(String pattern, String text) {
System.out.println(String.format("%s => %s : %s", pattern, text, ant.match(pattern, text)));
}