Ant 风格路径表达式
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 | java |
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 | // 扫描com.example.service包及其所有子包 |
3.4.AOP切点表达式
虽然AOP主要用AspectJ语法,但有时也会用Ant风格路径来匹配包名或方法名
3.5.配置文件拦截 (Spring Security)
1 |
|
注意:在Spring Security的最新版本中,antMatcher 已被更现代的 requestMatchers 所取代,但其底层匹配逻辑依然是Ant风格。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 Khalid博客!