Custom annotation @RequestMapping
I have multiple methods in my spring controllers that show up in the same path for 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 set the 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 purpose of this is to follow all of my controllers (e.g. user, order, customer) extends a parameterized BaseController that includes a basic set of functions (get by id, save, update, delete, etc.). All logic is on BaseController, but in order to map the value I have to add annotation to a specific controller. Instead of writing {id} and post all the time, I would like to annotate the methods with a custom interface that already includes these values
source to share
The following works for Spring 4.1.x that I have 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);
}
as you mention.
This kind of annotation was Spring calls meta annotation. Check this piece of documentation
I'm not sure if this meta-annotation will work in versions of Spring prior to 4.x, but it is definitely possible since Spring had some meta-annotation handling capabilities on line 3.x
If you are using Groovy you can also take advantage of the @AnnotationCollector
AST, which will actually keep duplication from the source code, but will nudge regular annotation @RequestMapping
into the resulting bytecode. See here for details .
The advantage in this case would be that Spring does not have to be equipped with meta-annotation reading capabilities, and where the solution might work with older versions of Spring
source to share