【问题标题】:Encapsulate annotation default value by composing RequestParam annotation in spring在spring中通过组合RequestParam注解来封装注解默认值
【发布时间】:2020-05-20 08:38:46
【问题描述】:

如果我在 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 not applicable to annotation type”:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestParam(value = "amount", defaultValue = "10")
public @interface MyAmountAnnotation {
    //...

我可以这样做以将详细注释“封装”到专门的注释吗?怎么了?

【问题讨论】:

    标签: java spring


    【解决方案1】:

    我认为您可以创建 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) {..
    

    希望对你有帮助

    【讨论】:

    • 嗯,我不确定它是否正确,你试过了吗?我得到'可选的int参数'amount'存在,但由于被声明为原始类型而无法转换为空值。考虑将其声明为相应原始类型的对象包装器。我已经尝试将 boolean required() 默认设置为 true 和 false。
    • @Adam 尝试在函数上定义金额参数,例如 @MyAmountAnnotation Integer amount 而不是 @MyAmountAnnotation int amount
    • 不,这也不起作用,我不了解 Spring 引擎盖下发生的反射魔法。但感觉“RequestParam”注释不能只是被换掉而不是它的一部分,就像链接博客中的撰写风格一样。
    • @Adam 我已经测试过了,对我来说似乎工作正常
    • @Adam 将int 更改为Integer 后出现什么错误?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-11
    • 1970-01-01
    • 2015-09-14
    相关资源
    最近更新 更多