请求参数的自定义Spring注释

时间:2015-06-08 17:33:43

标签: java spring spring-mvc spring-annotations request-mapping

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

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

我可以制作注释@UpperCase:

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

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

1 个答案:

答案 0 :(得分:33)

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

  1. 创建注释,例如
  2. @Target(ElementType.PARAMETER)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface UpperCase {
        String value();
    }
    
    1. 写一个解析器,例如
    2. 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. 注册一个解析器
      2. <mvc:annotation-driven>
                <mvc:argument-resolvers>
                    <bean class="your.package.UpperCaseResolver"></bean>
                </mvc:argument-resolvers>
        </mvc:annotation-driven>
        

        或java config

            @Configuration
            @EnableWebMvc
            public class Config extends WebMvcConfigurerAdapter {
            ...
              @Override
              public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
                  argumentResolvers.add(new UpperCaseResolver());
              }
            ...
            }
        
        1. 在控制器方法中使用注释,例如
        2. public String test(@UpperCase("foo") String foo)