处理程序映射的显式注册

时间:2018-10-16 10:38:38

标签: spring spring-mvc handler

我正在阅读Spring文档中更具体的处理程序映射部分,并且知道我们可以在运行时注册处理程序映射方法。我知道它是如何完成的,但是我无法掌握的是为什么我们首先需要这种功能?

请参阅以下代码段以注册处理程序。

@Autowired
  public void setHandlerMapping(RequestMappingHandlerMapping mapping, HelloRestController handler) 
        throws NoSuchMethodException {

    RequestMappingInfo info = RequestMappingInfo
            .paths("/mycustomapi").methods(RequestMethod.GET).build(); 
    Method method = HelloRestController.class.getMethod("customHandler"); 
    mapping.registerMapping(info, handler, method); 
}

Documentation

如果有人可以解释一些需要的用例,那么这将对您有所帮助。

1 个答案:

答案 0 :(得分:2)

我从没使用过,但是这里有一个我能想到的实用程序:

由于注释仅接受常量表达式作为参数,因此您不能编写如下内容:

 @ViewChild(Slides) slides: Slides;

 // and then after remove item call this
 this.slides.update();

但是你可以这样写:

@GetMapping(requestMapping(...)) // The value for annotation GetMapping.value must be a constant expression
public String customHandler(...) {
 ...
}

换句话说,您可以编写计算出的URI处理程序(例如,存储在配置文件中)。