基于Spring Boot利用@Deprecated实现HTTP响应废弃头方案问询
基于@Deprecated注解自动添加API废弃响应头的Spring Boot实现方案
核心思路
借助Spring MVC的拦截器机制,在请求处理完成后自动检测目标Controller方法或类上的@Deprecated注解,为符合条件的API响应自动注入标准废弃头字段,无需逐个修改端点代码。
具体实现步骤
1. 自定义废弃API拦截器
创建实现HandlerInterceptor的拦截器,重写postHandle方法完成注解检测与响应头注入:
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; public class DeprecatedApiInterceptor implements HandlerInterceptor { @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // 仅处理Controller方法类型的请求 if (!(handler instanceof HandlerMethod handlerMethod)) { return; } // 检查方法或所属类是否标注@Deprecated boolean isDeprecated = handlerMethod.getMethod().isAnnotationPresent(Deprecated.class) || handlerMethod.getBeanType().isAnnotationPresent(Deprecated.class); if (isDeprecated) { // 注入标准废弃头字段 response.setHeader("Deprecation", "true"); // 可选:添加废弃截止时间(遵循RFC 7231日期格式) response.setHeader("Sunset", "2025-12-31T23:59:59Z"); // 可选:添加替代API链接(遵循RFC 5988格式) response.setHeader("Link", "</v2/users>; rel=\"alternate\""); } } }
2. 注册拦截器到Spring MVC
通过配置类将拦截器加入Spring MVC的拦截器链,指定需要拦截的API路径:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new DeprecatedApiInterceptor()) .addPathPatterns("/api/**"); // 可根据实际API路径调整匹配规则 } }
扩展优化方向
- 自定义增强注解:如果需要携带废弃原因、替代说明等额外信息,可以自定义
@ApiDeprecated注解,在拦截器中读取注解属性并注入X-Deprecation-Reason等自定义响应头。 - 配置化管理:将废弃截止时间、默认替代链接等参数抽离到配置文件,提升灵活性。
- 调用日志统计:在拦截器中添加日志记录,统计废弃API的调用频次与来源,便于后续通知调用方迁移。
内容的提问来源于stack exchange,提问作者Farooq Shanawaz
相关产品推荐
相关产品推荐

