java 请求参数的自定义 Spring 注释

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30715579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:33:21  来源:igfitidea点击:

Custom Spring annotation for request parameters

javaspringspring-mvcspring-annotationsrequest-mapping

提问by arminas

I would like to write custom annotations, that would modify Spring request or path parameters according to annotations. For example instead of this code:

我想编写自定义注释,根据注释修改 Spring 请求或路径参数。例如,而不是此代码:

@RequestMapping(method = RequestMethod.GET)
public String test(@RequestParam("title") String text) {
   text = text.toUpperCase();
   System.out.println(text);
   return "form";
}

I could make annotation @UpperCase :

我可以注释 @UpperCase :

@RequestMapping(method = RequestMethod.GET)
   public String test(@RequestParam("title") @UpperCase String text) {
   System.out.println(text);
   return "form";
}

Is it possible and if it is, how could I do it ?

是否可能,如果可能,我该怎么做?

回答by Master Slave

As the guys said in the comments, you can easily write your annotation driven custom resolver. Four easy steps,

正如这些人在评论中所说,您可以轻松编写注释驱动的自定义解析器。四个简单的步骤,

  1. Create an annotation e.g.
  1. 创建一个注释,例如


@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface UpperCase {
    String value();
}
  1. Write a resolver e.g.
  1. 写一个解析器,例如


public class UpperCaseResolver implements HandlerMethodArgumentResolver {

    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterAnnotation(UpperCase.class) != null;
    }

    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
            WebDataBinderFactory binderFactory) throws Exception {
        UpperCase attr = parameter.getParameterAnnotation(UpperCase.class);
        return webRequest.getParameter(attr.value()).toUpperCase();
    }
}
  1. register a resolver
  1. 注册解析器


<mvc:annotation-driven>
        <mvc:argument-resolvers>
            <bean class="your.package.UpperCaseResolver"></bean>
        </mvc:argument-resolvers>
</mvc:annotation-driven>

or the java config

或 java 配置

    @Configuration
    @EnableWebMvc
    public class Config extends WebMvcConfigurerAdapter {
    ...
      @Override
      public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
          argumentResolvers.add(new UpperCaseResolver());
      }
    ...
    }
  1. use an annotation in your controller method e.g.
  1. 在您的控制器方法中使用注释,例如


public String test(@UpperCase("foo") String foo)