2

Why I must use @RequestParam annotation on implementation class instead of interface class only? I'm using interface and implementation in separate files approach. It seems that usage of @RequestParam on interface has no effect.

public interface GreetingService {

    @RequestMapping(value = "/greeting", method = RequestMethod.GET)
    public Greeting greetingByGet(@RequestParam(value="name", defaultValue="World") String name);

}

@RestController
public class GreetingController implements GreetingService {

    @Override
    public Greeting greetingByGet(
    /** 
    * Why do I need to duplicate @RequestParam annotation on 
    * implementation to make it work ??? 
    * Otherwise GET default value is not used. 
    */ 
    @RequestParam(value="name", defaultValue="World")
    String name) {

        ...
    }
}

It make sense for annotations like @Transactional which are implementation specific but are @RequestParam, @RequestBody, etc. implementation specific? Or this is a part of interface contract? @RequestBody(required) suggest it is a part of contract so using it on interface should be supported.

There is an explanation here: Spring MVC Annotated Controller Interface but the question is: Is there more general idea behind this explanation? Or only Spring internals force us to do it like it is now?

It is hard to understand why annotations are not inherited to implementation.

Community
  • 1
  • 1
tjuchniewicz
  • 103
  • 1
  • 7

1 Answers1

6

Java does not provide inheritance for annotations on interfaces, nor for methods or method parameters. While there is an @Inherited annotation, it works only at the class level, see http://docs.oracle.com/javase/8/docs/api/java/lang/annotation/Inherited.html

So this is not due to Spring or a design decision, it is about the Java language design.

Thomas
  • 11,272
  • 2
  • 24
  • 40
  • So maybe Spring annotations should be annotated with `@Inherited`? For me and for some my colleagues it is more clear to annotate interfaces with metadata like `@RequestParam` than implementation classes. – tjuchniewicz May 04 '16 at 08:10
  • You can not inherit method level annotation in Java (yet), neither method parameters. So it currently can't be done, although your wish is understandable. – Thomas May 04 '16 at 08:11