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.
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
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?
I suggest to simply use inheritance for that:
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
- 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.