如何根据HTTP标头值在RestControllers之间切换?

我们正在考虑使用标头字段在我们的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


慕桂英4014372
浏览 144回答 2
2回答

鸿蒙传说

这似乎可行:@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:尚未测试,但已在Spring引导教程中看到。

幕布斯7119047

确实是:例如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);}在这里您可以获得文档: 添加自定义标头
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java