自定义@RequestMapping注解

Custom @RequestMapping annotation

我的 spring 控制器中映射到同一路径的方法很少,例如。

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    protected ResourceDTO getById(@PathVariable int id) {
        return super.getById(id);
    }

我想知道是否有一种方法可以创建一个自动具有设置值和方法的注释,使其具有如下内容:

    @RequestMappingGetByID
    protected ResourceDTO getById(@PathVariable int id) {
        return super.getById(id);
    }

祝大家有个愉快的一天

更新 这样做的目标如下 我所有的控制器(例如用户、订单、客户端)都扩展了一个参数化的 BaseController,它包括一组基本功能(通过 id 获取、保存、更新、删除等)所有逻辑都在 BaseController 上,但为了映射值我必须在特定控制器上添加注释。 我不想一直写 {id} 和 post 我想用一个已经包含这些值的自定义接口来注释方法

以下适用于我测试的 Spring 4.1.x:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@interface RequestMappingGetByID {

}

然后你可以使用

@RequestMappingGetByID
protected ResourceDTO getById(@PathVariable int id) {
    return super.getById(id);
}

就像你提到的那样。

这种注释是 Spring 调用元注释。查看文档的 this 部分

我不确定这个元注释是否可以在 4.x 之前的 Spring 版本中工作,但这绝对是可能的,因为 Spring 在3.x行


如果您在使用 Groovy 的地方,您还可以利用 @AnnotationCollector AST,这实际上会将重复排除在您的源代码之外,但会推动常规 @RequestMapping 注释到生成的字节码中。查看 this 了解更多详情。

这种情况下的好处是 Spring 不需要配备元注释读取功能,并且该解决方案可能适用于较旧的 Spring 版本