base-package 详解

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:

解析步骤:

  1. 解析占位符
  2. 将“.”替换为“/”
  3. 追加 “/**/*.class”
  4. 由ResourcePatternResolver接口(默认采用 PathMatchingResourcePatternResolver实现)加载资源

PathMatchingResourcePatternResolver#findPathMatchingResources 源码

解析步骤:

  1. 将locationPattern分割为两部分,第一部分(rootDirPath)不包含匹配符,第二部分(subPattern)包含匹配符
  2. 获取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)));
	}
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值