在Spring 3.2 MVC中实现API版本的API版本 [英] API versioning with fall-through in Spring 3.2 MVC

查看:237
本文介绍了在Spring 3.2 MVC中实现API版本的API版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将现有的Web服务移植到Spring 3.2。我需要版本化的API,并为每个新版本都有一个控制器。我不想在较新的控制器中重新定义方法,而是想在最近找不到它时自动将请求映射到旧控制器。

I'm porting an existing web service to Spring 3.2. I need versioned APIs and have a controller for every new version. I do not want to re-defined methods in newer Controllers and instead want to automatically map requests to old controller if it's not found in the latest.

例如,如果 ControllerV1 / home / login ControllerV2 / login ,然后我希望请求像这样路由。

For example, if ControllerV1 has /home and /login and ControllerV2 has /login, then I want requests to be routed like this.

/home -> ControllerV1
/v1/home -> ControllerV1
/v2/home -> ControllerV1

/login -> ControllerV1
/v1/login -> ControllerV1
/v2/login -> ControllerV2

一个选项是在 @RequestMapping 。但是,这意味着每当在较新版本中添加API时,都会从所有旧控件中删除路径。实现这一目标最优雅的方法是什么?

One option would be to provide multiple paths in @RequestMapping. However, that would mean removing paths from all older controllesr whenever adding the API in a newer version. What is the most elegant way to achieve this?

推荐答案

我建议只使用继承:

Version1Controller.java

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("v1/")
public class Version1Controller {

    @ResponseBody
    @RequestMapping("foo")
    public String foo() {
        return "Foo 1";
    }

    @ResponseBody
    @RequestMapping("bar")
    public String bar() {
        return "bar 1";
    }
}

Version2Controller.java

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping({ "v2/", "latest/" })
public class Version2Controller extends Version1Controller {

    @Override
    @ResponseBody
    @RequestMapping("bar")
    public String bar() {
        return "bar 2";
    }

}

这里你将有以下网址映射:

Here you will have following urls mapped:


  • v1 / foo - 返回Foo 1

  • v2 / foo - 返回Foo 1 - 继承自版本1

  • v1 / bar - 返回Bar 1

  • v2 / bar - 返回Bar 2 - 从版本1覆盖行为。

  • latest / foo - 与 v2 / foo相同

  • latest / bar - 与 v2 / bar相同

  • v1/foo - returning "Foo 1"
  • v2/foo - returning "Foo 1" - inherited from Version 1
  • v1/bar - returning "Bar 1"
  • v2/bar - returning "Bar 2" - overriding behavior from Version 1.
  • latest/foo - same as v2/foo
  • latest/bar - same as v2/bar

这篇关于在Spring 3.2 MVC中实现API版本的API版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆