1.概述

简单来说,它是一种用来匹配文件路径或URL路径的特殊字符串,使用通配符来定义一种模式。只要真实的路径符合这个模式,就表示匹配成功。

它最初是Apache Ant这个构建工具的一部分(用于通配地选择文件),因为非常直观和强大,后来被广泛引入到Spring框架等众多Java项目中,用于资源查找、URL映射、文件拦截等场景。

2.ANT通配符

通配符 说明 示例 匹配示例 不匹配示例
? 匹配任何单字符 config?.xml config1.xml, configA.xml config10.xml
* 匹配0或者任意数量的字符 *.xml pom.xml, application.xml config/spring.xml
** 匹配0或者更多的目录 /resources/** /resources/, /resources/1.png, /resources/css/style.css /public/1.png

2.1示例

URL路径 说明
/app/*.x 匹配(Matches)所有在app路径下的.x文件
/app/p?ttern 匹配(Matches) /app/pattern 和 /app/pXttern,但是不包括/app/pttern
/**/example 匹配(Matches) /app/example, /app/foo/example, 和 /example
/app/**/dir/file.* 匹配(Matches) /app/dir/file.jsp, /app/foo/dir/file.html,/app/foo/bar/dir/file.pdf, 和 /app/dir/file.java
/**/*.jsp 匹配(Matches)任何的.jsp 文件

2.2.最长匹配原则(has more characters)

URL请求/app/dir/file.jsp,现在存在两个路径匹配模式/**/.jsp和/app/dir/.jsp,那么会根据模式/app/dir/*.jsp来匹配

3.在Spring框架中的常见应用场景

3.1.URL请求映射 (Spring MVC)

1
2
3
4
5
6
7
8
9
java
@RestController
@RequestMapping("/api/v1/**") // 匹配所有以 /api/v1/ 开头的请求
public class MyController {
@GetMapping("/users/*") // 匹配例如 /api/v1/users/123
public User getUser() {
// ...
}
}

3.2.资源位置 (Spring Boot静态资源)

application.properties或配置类中,指定静态资源的位置。

1
spring.web.resources.static-locations=classpath:/META-INF/resources/, classpath:/resources/, classpath:/static/, classpath:/public/, file:/opt/static/

3.3.组件扫描 (Component Scan)

1
@ComponentScan("com.example.service.**") // 扫描com.example.service包及其所有子包

3.4.AOP切点表达式

虽然AOP主要用AspectJ语法,但有时也会用Ant风格路径来匹配包名或方法名

3.5.配置文件拦截 (Spring Security)

1
2
3
4
5
6
7
8
9
10
@Configuration
@EnableWebSecurity
public class SecurityConfig {
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/public/**", "/resources/**").permitAll() // 放行所有公共资源和静态资源
.antMatchers("/admin/**").hasRole("ADMIN") // 匹配/admin下的所有路径,需要ADMIN角色
.anyRequest().authenticated(); // 任何其他请求都需要认证
}
}

注意:在Spring Security的最新版本中,antMatcher 已被更现代的 requestMatchers 所取代,但其底层匹配逻辑依然是Ant风格。