You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Spring Boot指定包下的控制器添加自定义前缀

给同包控制器批量添加自定义前缀的解决方案

你可以通过以下几种方式实现给指定包下的控制器批量添加自定义前缀,无需逐个修改@RequestMapping:

方法一:基于自定义注解批量配置

这种方式灵活性高,可按需给任意控制器添加前缀,也能按包批量标注注解。

  1. 定义自定义前缀注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ControllerPrefix {
    String value(); // 指定前缀内容
}
  1. 给目标包下的控制器添加该注解
    比如你的MyController所在包的所有控制器都加上这个注解:
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/families")
@RolesGuard(role = {Roles.Manager, Roles.Employee})
@ControllerPrefix("/family-api") // 添加自定义前缀
public class MyController {
    // 控制器逻辑...
}
  1. 配置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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 20:15:03