如何为Spring Boot指定包下的控制器添加自定义前缀
给同包控制器批量添加自定义前缀的解决方案
你可以通过以下几种方式实现给指定包下的控制器批量添加自定义前缀,无需逐个修改@RequestMapping:
方法一:基于自定义注解批量配置
这种方式灵活性高,可按需给任意控制器添加前缀,也能按包批量标注注解。
- 定义自定义前缀注解
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface ControllerPrefix { String value(); // 指定前缀内容 }
- 给目标包下的控制器添加该注解
比如你的MyController所在包的所有控制器都加上这个注解:
@Slf4j @RestController @AllArgsConstructor @RequestMapping("/families") @RolesGuard(role = {Roles.Manager, Roles.Employee}) @ControllerPrefix("/family-api") // 添加自定义前缀 public class MyController { // 控制器逻辑... }
- 配置WebMvc规则实现前缀拼接
@Configuration public class WebMvcPrefixConfig implements WebMvcConfigurer { @Override public void configurePathMatch(PathMatchConfigurer configurer) { // 给带有@RestController和@ControllerPrefix的控制器添加前缀 configurer.addPathPrefix("/{prefix}", handlerType -> handlerType.isAnnotationPresent(RestController.class) && handlerType.isAnnotationPresent(ControllerPrefix.class) ); } // 自定义前缀生成器,从注解中获取前缀值 @Bean public PathPrefixHandlerMapping pathPrefixHandlerMapping() { PathPrefixHandlerMapping mapping = new PathPrefixHandlerMapping(); mapping.setPrefixGenerator(handlerType -> { ControllerPrefix prefixAnnotation = handlerType.getAnnotation(ControllerPrefix.class); return prefixAnnotation != null ? prefixAnnotation.value() : ""; }); return mapping; } }
方法二:基于包路径自动匹配前缀
如果控制器已经按功能严格分包(如xxx.families、xxx.products),可以直接通过包路径批量添加前缀,无需给每个控制器加注解。
@Configuration public class PackageBasedPrefixConfig implements WebMvcConfigurer { @Override public void configurePathMatch(PathMatchConfigurer configurer) { // 给families包下的所有控制器添加前缀/family-api configurer.addPathPrefix("/family-api", handlerType -> handlerType.getBean().getClass().getPackageName().contains(".families.") ); // 给products包下的所有控制器添加前缀/product-api configurer.addPathPrefix("/product-api", handlerType -> handlerType.getBean().getClass().getPackageName().contains(".products.") ); // 其他包按同样逻辑添加即可 } }
注意事项
- 前缀会自动拼接在控制器原有
@RequestMapping路径的前面,比如原路径/families会变成/family-api/families,全局context-path会在最外层,最终路径为{context-path}/family-api/families - 两种方法都不会影响未匹配的控制器,其他包的控制器路径保持不变
内容的提问来源于stack exchange,提问作者Sparks
相关产品推荐
相关产品推荐

