【问题标题】:How to switch between RestControllers depending on HTTP header values?如何根据 HTTP 标头值在 RestController 之间切换?
【发布时间】:2018-12-05 01:49:08
【问题描述】:

我们正在考虑在我们的 Spring Boot 应用程序中使用标头字段来指定 REST API 版本。

我们如何告诉 Spring Boot 根据标头值重定向调用?

我梦想着这样的事情:

@Path("/my/rest/path")
@HeaderMapping(headerName="ApiVersion", headerValue="V1")
public class V1Controller {

    @GetMapping
    public String myMethod() {
    }
}

== and ==

@Path("/my/rest/path")
@HeaderMapping(headerName="ApiVersion", headerValue="V2")
public class V2Controller {

    @GetMapping
    public String myMethod() {
    }
}

对于这样的 HTTP 请求:

GET /my/rest/path HTTP/1.1
Accept: application/json
ApiVersion: V1

== or ==

GET /my/rest/path HTTP/1.1
Accept: application/json
ApiVersion: V2

【问题讨论】:

    标签: java spring rest spring-boot api-versioning


    【解决方案1】:

    这似乎有效:

    @Path("/my/rest/path")
    public class V1Controller {
    
        @GetMapping(headers = "ApiVersion=V1")
        public String myMethod() {
        }
    }
    
    == and ==
    
    @Path("/my/rest/path")
    public class V2Controller {
    
        @GetMapping(headers = "ApiVersion=V2")
        public String myMethod() {
        }
    }
    

    PS:尚未测试,但在 a Spring boot tutorial 中看到。

    【讨论】:

      【解决方案2】:

      没错: 例如

      PUT method #1
      @RequestMapping(method=RequestMethod.PUT, value="/foo", 
      headers="returnType=Foo")
      public @ResponseBody Foo updateFoo(@RequestBody Foo foo) {
      fooService.update(foo);
      }
      
      //PUT method #2
      @RequestMapping(method=RequestMethod.PUT, value="/foo", 
      headers="returnType=FooExtra")
      public @ResponseBody FooExtra updateFoo(@RequestBody FooExtra fooExtra) {
      fooService.update(fooExtra);
      }
      

      在这里您可以获得文档: adding custom header

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        • 2011-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-03
        相关资源
        最近更新 更多