spring rest api 版本控制

标签 spring rest web-services spring-mvc

在我的 spring Controller 中,我有 2 个 rest api 方法。示例:getUser、getRole
一个客户端通过“/api/v1”之类的方式访问它。
现在我想更新其中一种方法。即,getRole。所以新的方法/版本将是“/api/v2”。
但是 v1 的方法没有变化。即,“/api/v1”。

如何在同一个项目中处理两个版本的其余方法?
我的意思是,getUser rest API 应该同时支持“/api/v1”和“/api/v2”。
并且 getRole rest API 应该支持两个版本但不同的功能(例如:数据库更改,逻辑更改)。
简单来说,
1. getUser 将有 1 个支持两个版本的方法。
2. getRole 每个版本有 2 个方法。

请在这里帮助我。

最佳答案

如果你想为两个版本使用单独的方法,你可以通过在 @RequestMapping 中定义不同的值

方法一

    @RequestMapping(
                value = "baseurl/v1/role",
                method = RequestMethod.GET,
                produces = MediaType.APPLICATION_JSON_VALUE)

   and


    @RequestMapping(
                    value = "baseurl/v2/role",
                    method = RequestMethod.GET,
                    produces = MediaType.APPLICATION_JSON_VALUE)

但如果你想用同样的方法处理它,你可以使用

方法二:使用@PathVariable
@RequestMapping(
            value = "baseurl/{version}/role",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
public returnType methodName(@PathVariable("version") String version){

// code to check version

}

方法三:使用@RequestHeader
@RequestMapping(
                value = "baseurl/role",
                method = RequestMethod.GET,
                produces = MediaType.APPLICATION_JSON_VALUE)
    public returnType methodName(@RequestHeader("version") String version){

    // code to check version

    }

但是正如您所说,您有不同版本的 api,更喜欢使用 @RequestMapping 在单独的 Controller 中管理它们。在类(class)

方法四:
@RestController
@RequestMapping("/v1")
public class anyController {

}

and 

@RestController
@RequestMapping("/v2")
public class anyController {

}

关于spring rest api 版本控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45438362/

相关文章:

java - 使 Tomcat 忽略 WEB-INF/LIB 中的 Servlet

java - 将列表存储在表列中

java - 在 Eclipse (3.6 Helios) 中使用 Spring (3.0.5)

spring - 使用 RabbitMQ 的自定义目的地

ios - 如何在ios中多次调用同一个服务并存储数据

.net - 如何将 httpRuntime maxRequestLength ="8096"集成到 app.config [Webservices]

java - 使用 Spring 包装类相对于 Quartz 调度程序库的优势

ruby-on-rails - 是否有 RESTful 方式为 habtm 配置路由?

java - Spring Boot 中的子 Controller

node.js - Node : serving secure (wss://) and insecure (ws://) connections with the same server