Spring HATEOAS - 构建强大且可扩展的解决方案

时间:2016-07-13 03:12:19

标签: java spring rest hateoas spring-hateoas

让我们考虑一下我有一个带有3个服务的REST控制器。我有以下代码来相互添加链接:

@RestController
public class ServiceController {


  @RequestMapping("/service1")
  public HttpEntity<Response> service1() {

      Response response = new Response("You are in service 1");

      response.add(linkTo(methodOn(ServiceController.class).service1()).withSelfRel());
      response.add(linkTo(methodOn(ServiceController.class).service2()).withRel("service2"));
      response.add(linkTo(methodOn(ServiceController.class).service3()).withRel("service3"));

      return new ResponseEntity<Response>(response, HttpStatus.OK);
  }

  @RequestMapping("/service2")
  public HttpEntity<Response> service2() {

      Response response = new Response("You are in service 2");

      response.add(linkTo(methodOn(ServiceController.class).service1()).withRel("service1"));
      response.add(linkTo(methodOn(ServiceController.class).service2()).withSelfRel());
      response.add(linkTo(methodOn(ServiceController.class).service3()).withRel("service3"));

      return new ResponseEntity<Response>(response, HttpStatus.OK);
  }

  @RequestMapping("/service3")
  public HttpEntity<Response> service3() {

      Response response = new Response("You are in service 3");

      response.add(linkTo(methodOn(ServiceController.class).service1()).withRel("service1"));
      response.add(linkTo(methodOn(ServiceController.class).service2()).withRel("service2"));
      response.add(linkTo(methodOn(ServiceController.class).service3()).withSelfRel());

      return new ResponseEntity<Response>(response, HttpStatus.OK);
  }
}

虽然这有效,但它不是非常强大或可扩展。每次我必须修改/删除服务时,我必须找到它的所有实例并进行更改。如果我创建一项新服务,我将不得不将该新服务的链接复制到服务1 - 3.(此外,还有大量重复代码。)

重构此代码的最佳方法是什么?将这个链接代码完全移出服务是否有意义?

0 个答案:

没有答案