Home > database >  can an annotation modify function signature in spring boot?
can an annotation modify function signature in spring boot?

Time:10-02

this seems kind of simple, but i have never created annotations in spring boot. im not sure if the following requirement can be done using spring custom annotations...or do i need to use something like google/auto or lombok for it

I have many routes with exactly the same function signature. only the routes differ.

@RequestMapping(value = {"/article", "/article/{id}", "/article/{name}"}, method = RequestMethod.GET,
                consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
 
  public ResponseEntity<JsonNode> get(@PathVariable Map<String, String> pathVarsMap, @RequestParam(value="test") MultiValueMap<String, String> test, @RequestBody(required=false) JsonNode requestBody ) {}

can i write a custom annotation that takes the following, and converts this to the function declaration and signature defined above?

@MyAnnotation(value = {"/article", "/article/{id}", "/article/{name}"})
public void get()

this is compile time, so if the return type is not of ResponseEntity<JsonNode> (after annotation causes function signature to be replaced), it should still give a compilation error.

CodePudding user response:

Unfortunately you can't do this with Spring.

Spring work in runtime, so code already compiled when it starts. So you can't change method signatures.

You can achieve you goal using compile time annotation processing though.

CodePudding user response:

You definitely can't change methods signatures using plain Spring, as mentioned talex. Moreover, it's not so clear why you even need to change Java method signatures. All this magic that you wanna apply will overcomplicate the code and decrease readability significantly. Probably it’s the wrong way.

If you just need to create your own annotation that will replace the default @RequestMapping annotation, you can create your own annotation and apply org.springframework.core.annotation.AliasFor:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@RequestMapping(method = RequestMethod.GET,
        consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,
        produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public @interface MyAnnotation {
    @AliasFor(annotation = RequestMapping.class)
    String[] value() default {};
}

In that case, you won’t change methods signatures, but you will be able to reuse your @MyAnnotation in that way:

@MyAnnotation(value = {"/article", "/article/{id}", "/article/{name}"})
public ResponseEntity<JsonNode> get(@PathVariable Map<String, String> pathVarsMap, @RequestParam(value="test") MultiValueMap<String, String> test, @RequestBody(required=false) JsonNode requestBody ) {}

If you still sure, that you have to change Java methods signatures, you can try to use Lombok Custom annotations for that. There is the good answer how to do so.

  • Related