【问题标题】:Custom Spring annotation for request parameters - custom resolver never invoked请求参数的自定义 Spring 注释 - 从未调用自定义解析器
【发布时间】:2018-08-06 01:41:00
【问题描述】:

我在我的项目中实现了自定义注解,但从未调用实现的方法参数解析器。 有人可以帮我解决这个问题吗?

我的实现:

注释

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation {
    String value();
}

解析器

public class MyAnnotationResolver implements HandlerMethodArgumentResolver {

   public boolean supportsParameter(MethodParameter parameter) {
         System.out.println("supportsParameter invoked!");
         return parameter.getParameterAnnotation(MyAnnotation.class) != null;
   }

   public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
WebDataBinderFactory binderFactory) throws Exception {
        ...
        return "someString";
    }
}

配置

@Configuration
@EnableWebMvc 
public class Config extends WebMvcConfigurerAdapter { 
  ...   
   @Override   
   public void addArgumentResolvers(List<HandlerMethodArgumentResolver>  argumentResolvers) {
      argumentResolvers.add(new MyAnnotationResolver());
      System.out.println("Resolver added!");   
   } 
... 
}

控制器

@Controller
@RequestMapping("/project")
public class ProjectController{

    @RequestMapping(method = RequestMethod.GET, value= "/{hashCode}")
    @ResponseBody
    public String index(@MyAnnotation("hashCode") String hashCode, Model model) {
    ...
    System.out.println(hashCode == null ? "HashCode=null" : "HashCode=" + hashCode);
}   

作为输出我得到:

Resolver added!

HashCode=null

为什么从未调用过 supportsParameter(...)?

【问题讨论】:

    标签: spring-mvc spring-annotations resolver


    【解决方案1】:

    这是不可复制的。使用给定代码调用supportsParameter。

    自从您提出问题后 3 年过去了,我检查了您发布此问题时使用的 the code。不过相关代码并没有太大变化。

    一种可能的解释是有一个参数解析器支持该参数,因为它在找到另一个时不会检查另一个。

    【讨论】:

      猜你喜欢
      • 2015-08-23
      • 2019-12-24
      • 2016-06-08
      • 1970-01-01
      • 2023-01-27
      • 1970-01-01
      • 2021-02-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多