Search code examples
springannotationsrequest-mapping

Custom @RequestMapping annotation


I have few methods in my spring controllers which are mapped on the same path, example.

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

I was wondering if there is a way to create an annotation that will automatically have set value and method, to have something like this:

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

Have a nice day everyone

Update The goal of this is the following all my controllers (eg. user, order, client) extends a parametrized BaseController that includes a base set of function (get by id, save, update, delete, etc) All the logic is on the BaseController, but in order to map the value I have to add the annotation on the specific controller. Instead of writing all the time {id} and post I would like to annotate the methods with a custom interface that already includes those values


Solution

  • The following works for Spring 4.1.x that I tested:

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

    Then you can use

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

    like you mention.

    This kind of annotation is was Spring calls a meta-annotation. Check out this part of the documentation

    I am not sure if this meta-annotation would work in versions of Spring prior to 4.x, but it's definitely possible since Spring had some meta-annotation handling capabilities in the 3.x line


    If you where using Groovy, you could also take advantage of the @AnnotationCollector AST, which in effect would keep the duplication out of your source code, but would push the regular @RequestMapping annotation into the produced bytecode. Check out this for more details.

    The benefit in this case would be that Spring need not have to be equipped with the meta-annotation reading capabilities, and there for the solution possibly works on older Spring versions