升级Spring Boot 2.5.6后@BasePathAwareController类用@RequestMapping报错如何解决
根因说明
Spring Boot 2.5.6配套的Spring Data REST 3.5.x版本新增了校验逻辑:标注了@BasePathAwareController的控制器禁止在类级别添加@RequestMapping注解,防止路径重复注册,这就是你启动报错的直接原因。
可行解决方案(不需要逐个拼接方法路径)
方案1:Spring MVC全局路径前缀配置
直接在现有配置类中扩展WebMvcConfigurer,给指定范围的控制器统一加前缀,零侵入修改业务代码:
@Configuration public class RestModuleConfiguration implements RepositoryRestConfigurer, WebMvcConfigurer { // 新增路径前缀配置 @Override public void configurePathMatch(PathMatchConfigurer configurer) { // 匹配规则可自定义:比如指定包路径下的所有@BasePathAwareController统一加/my前缀 configurer.addPathPrefix("/my", clazz -> clazz.isAnnotationPresent(BasePathAwareController.class) && clazz.getPackage().getName().startsWith("你的控制器所在包路径") ); } // 保留原有RepositoryRest配置 @Override public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config, CorsRegistry cors) { config.setReturnBodyOnCreate(true); config.setReturnBodyOnUpdate(true); config.setBasePath(Constants.API_BASE_URI); // "/api" // 其余原有逻辑不变 } }
配置完成后直接删除控制器类上的@RequestMapping("/my")即可,方法上的@GetMapping("/x")不需要修改,最终访问路径为/api/my/x,完全符合你的预期。
方案2:自定义组合注解封装统一前缀
如果不同控制器前缀不一样,你可以为每个控制器自定义组合请求注解,把前缀封装到注解里:
// 自定义MyController专属的GetMapping注解 @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @GetMapping public @interface MyControllerGetMapping { String BASE_PREFIX = "/my/"; @AliasFor(annotation = GetMapping.class) String[] value() default {}; // 自动拼接前缀 @AliasFor(annotation = GetMapping.class) String[] path() default {}; }
使用时直接在方法上加@MyControllerGetMapping("x"),自动拼接为/my/x,其他Post、Put等请求类型可按相同逻辑自定义注解。
方案3:常量类统一管理前缀
如果需要灵活调整前缀,也可以在常量类中统一定义各个控制器的前缀:
public interface ControllerPrefixConstants { String MY_CONTROLLER_PREFIX = "/my"; // 其他控制器前缀同理 }
方法路径直接写为@GetMapping(ControllerPrefixConstants.MY_CONTROLLER_PREFIX + "/x"),后续调整前缀只需修改常量类一处即可。
内容的提问来源于stack exchange,提问作者Peters_
相关产品推荐
相关产品推荐

