如果我在spring中的控制器中有一个映射,比如:
@RequestMapping(params = "foo", method = RequestMethod.GET)
public String findAllBars(@RequestParam(value = "amount", defaultValue = "10") int amount, Model uiModel) {我可以做一个注释并封装上面的默认值10吗?像这样:
@RequestMapping(params = "foo", method = RequestMethod.GET)
public String findAllBars(@MyAmountAnnotation int amount, Model uiModel) {并让spring像预期的那样理解我的注释。我发现了https://stackabuse.com/spring-annotations-requestmapping-and-its-variants/,当我看到他们的@GetMapping,@PostMapping等人做了什么时,我有了一点希望。
然而,当我尝试的时候,我得到了编译错误'RequestParam不适用于注释类型‘:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestParam(value = "amount", defaultValue = "10")
public @interface MyAmountAnnotation {
//...我可以像这样把一个冗长的注解“封装”成一个专门的注解吗?怎么啦?
发布于 2020-02-04 21:59:25
我认为你可以像下面这样创建你的MyAmountAnnotation注释:
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAmountAnnotation {
@AliasFor("name")
String value() default "amount";
@AliasFor("value")
String name() default "amount";
boolean required() default true;
String defaultValue() default "10";
}并这样使用它:
@RequestMapping(params = "foo", method = RequestMethod.GET)
public String findAllBars(@MyAmountAnnotation int amount, Model uiModel) {..希望这能有所帮助
https://stackoverflow.com/questions/60058729
复制相似问题