I have created custom annotation like this
@Retention(RUNTIME)
@Target(METHOD)
@RequestMapping(consumes = { MediaType.APPLICATION_JSON_VALUE }, produces = {
MediaType.APPLICATION_JSON_VALUE }, method = RequestMethod.POST)
public @interface JsonPostMapping {
@AliasFor(annotation = RequestMapping.class, attribute = "value")
String[] value() default {};
@AliasFor(annotation = RequestMapping.class, attribute = "method")
RequestMethod[] method() default {};
@AliasFor(annotation = RequestMapping.class, attribute = "params")
String[] params() default {};
@AliasFor(annotation = RequestMapping.class, attribute = "headers")
String[] headers() default {};
@AliasFor(annotation = RequestMapping.class, attribute = "consumes")
String[] consumes() default {};
@AliasFor(annotation = RequestMapping.class, attribute = "produces")
String[] produces() default {};
}
I have the following controller
import com.config.requestmappings.JsonPostMapping;
@RestController
public class TestController {
@JsonPostMapping(value = "/hello")
public String hello() {
return "Hi, how are you";
}
}
The hello
api is also being called with GET request, i am expecting that it should only be called upon POST request.
CodePudding user response:
Remove the alias for method
in the annotation and use @PostMapping
instead of @RequestMapping
. Set the defaults in the body of the annotation itself.
@PostMapping
public @interface JsonPostMapping {
// ...
@AliasFor(annotation = PostMapping.class)
String[] consumes() default { MediaType.APPLICATION_JSON_VALUE };
@AliasFor(annotation = PostMapping.class)
String[] produces() default { MediaType.APPLICATION_JSON_VALUE };
}