根据不同包下统一各自api前缀
1. 代码实现
如何实现:实现Spring 提供的 WebMvcConfigurer接口,并添加前缀即可
⭐️项目结构图
⭐️依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<optional>true</optional>
</dependency>
<!-- validation -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
⭐️自定义web配置类
作用:
- 指定统一前缀
- 指定匹配包的路径
/**
* @author: zhanghp
* @date: 2022-07-03 0:12
*/
@Data
@Validated
@Component
public class WebProperties {
/**
* api包下统一前缀
*/
Api api = new Api("api-prefix", "**.controller.api.**");
/**
* admin包下统一前缀
*/
Api admin = new Api("admin-prefix", "**.controller.admin.**");
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class Api {
@NotEmpty
private String prefix;
@NotEmpty
private String controllerPath;
}
}
⭐️Web Config 类
Spring 官方提供的AntPathMatcher测试用例
作用: 实现api统一前缀处理
/**
* @author: zhanghp
* @date: 2022-07-03 0:16
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private WebProperties webProperties;
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
// 根据不同包匹配表达式,添加各自的统一前缀
configurePathMatch(configurer, webProperties.getApi());
configurePathMatch(configurer, webProperties.getAdmin());
}
/**
* API 前缀:实现指定的controller 提供的 RESTFul API 的统一前缀
*
* 意义:通过该前缀,避免Swagger,Actuator 意外通过Nginx暴露出来给外部,带来安全性问题
* 这样Nginx只需配置转发到 指定统一前缀 的所有接口即可
* @see org.springframework.util.AntPathMatcher
* @param configurer
* @param api
*/
private void configurePathMatch(PathMatchConfigurer configurer, WebProperties.Api api) {
// 创建路径匹配类,指定以'.'分隔
AntPathMatcher antPathMatcher = new AntPathMatcher(".");
// 指定匹配前缀
// 满足:类上有RestController注解 && 该类的包名匹配指定的自定义包的表达式
configurer.addPathPrefix(api.getPrefix(), clazz -> clazz.isAnnotationPresent(RestController.class)
&& antPathMatcher.match(api.getControllerPath(), clazz.getPackage().getName()));
}
}
⭐️Controller 层
-
AdminController
/** * @author: zhanghp * @date: 2022-07-03 0:07 */ @RestController public class AdminController { @GetMapping("/admin") public String apiTest(){ return "Admin Success"; } }
-
ApiController
/** * @author: zhanghp * @date: 2022-07-03 0:07 */ @RestController public class ApiController { @GetMapping("/api") public String apiTest(){ return "Api Success"; } }
2. 实现效果展示
-
访问 AdminController下的admin
localhost:8080/admin-prefix/admin
-
访问ApiController下的api
localhost:8080/api-prefix/api
⭐️源码:https://gitee.com/zhp1221/ruoyi/tree/master/lab_01_web_module/lab_01_api