1

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?

Chandra Sekar
  • 10,683
  • 3
  • 39
  • 54

1 Answers1

5

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
Ivan Sopov
  • 2,300
  • 4
  • 21
  • 39
  • What if the signature changes? Exemple : public String bar() will become public Integer bar() – LG_ May 21 '15 at 13:17