3

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

Aniket Kulkarni
  • 12,825
  • 9
  • 67
  • 90
Manza
  • 3,427
  • 4
  • 36
  • 57
  • See if it can help you http://howtodoinjava.com/2014/06/09/complete-java-annotations-tutorial/#create_custom_annotations – Jkike Aug 07 '15 at 13:12
  • Is the goal of the custom annotation to eliminate the `(value = "/{id}", method = RequestMethod.GET)`. Could you please elaborate on the intention of this? Would ALL your routes be GET requests and have the `id` path variable? – Alexander Staroselsky Aug 07 '15 at 13:12
  • Have you tried annotating `RequestMappingGetByID` with `@RequestMapping(value = "/{id}", method = RequestMethod.GET)`. It should work on Spring 4.x – geoand Aug 07 '15 at 13:12

1 Answers1

2

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

geoand
  • 60,071
  • 24
  • 172
  • 190