
本文介绍一种不依赖配置文件或路径变量的纯 Java 方式,通过反射与 Spring 的 RequestMappingHandlerMapping 在运行时动态注册/注销 REST 端点,实现如 /old 到 /new 的无缝切换。
本文介绍一种不依赖配置文件或路径变量的纯 java 方式,通过反射与 spring 的 `requestmappinghandlermapping` 在运行时动态注册/注销 rest 端点,实现如 `/old` 到 `/new` 的无缝切换。
在 Spring Boot 应用中,多数场景下接口路径由 @GetMapping、@PostMapping 等注解在编译期静态声明,无法更改。但某些特殊需求(如灰度发布、A/B 测试、运维热切换)要求在不重启服务的前提下动态变更端点映射关系。此时,直接操作 Spring MVC 的底层路由注册机制是可靠且可控的方案。
核心思路是:利用 Spring 内置的 RequestMappingHandlerMapping(负责管理所有 @RequestMapping 映射),通过 registerMapping() 和 unregisterMapping() 方法,在运行时移除旧路径并绑定新路径到指定处理方法。
以下是一个完整可运行的示例:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import java.lang.reflect.Method;
@RestController
@RequestMapping("/api/testing")
public class TestingController {
@Autowired
private RequestMappingHandlerMapping mappingHandler;
// 触发切换的控制端点
@GetMapping("/switch")
public String switchEndpoint() throws Exception {
// 1. 注销旧端点 /api/testing/old
RequestMappingInfo oldInfo = RequestMappingInfo.paths("/api/testing/old")
.methods(RequestMethod.GET)
.build();
mappingHandler.unregisterMapping(oldInfo);
// 2. 注册新端点 /api/testing/new,并指向 oldHandler 方法
RequestMappingInfo newInfo = RequestMappingInfo.paths("/api/testing/new")
.methods(RequestMethod.GET)
.build();
Method method = this.getClass().getDeclaredMethod("oldHandler");
mappingHandler.registerMapping(newInfo, this, method);
return "Switched: /old → /new";
}
// 实际业务逻辑方法(复用同一处理逻辑)
@GetMapping("/old")
public String oldHandler() {
return "✅ Response from old endpoint (now served via /new)";
}
}
✅ 关键说明:
-
oldHandler()方法本身仍保留@GetMapping("/old")注解——该注解仅用于启动时初始注册;运行时切换完全绕过它,由registerMapping()手动接管。 -
switchEndpoint()中调用unregisterMapping()后,原/old路径将立即返回404;而/new将精准响应,且共享相同业务逻辑。 -
Method对象必须通过反射获取(如getDeclaredMethod("oldHandler")),确保目标方法可被 Spring MVC 调用;若方法含参数或返回值,需确保签名兼容(本例为无参 void/string 返回,安全通用)。
⚠️ 注意事项:
- 此操作是非线程安全的,高并发调用
/switch可能引发竞态。建议加同步锁(如synchronized或ReentrantLock)或通过幂等设计(如仅允许切换一次)规避风险。 - 生产环境慎用:频繁注册/注销可能影响性能,且不利于可观测性(如 Actuator 的
/actuator/mappings会实时反映变更)。建议配合监控与告警使用。 - 不适用于
@RequestBody或复杂参数解析场景——因registerMapping()绑定的是原始Method,Spring 仍会按标准流程解析请求,只要方法签名匹配即可正常工作。
总结:该方案跳出了传统配置驱动或 URL 参数路由的限制,赋予开发者对 Web 路由生命周期的精细控制能力。它不是“魔法”,而是对 Spring MVC 设计哲学的一次深度实践——将 HandlerMapping 视为可编程资源,而非只读配置。











