春季启动+ REST + HATEOAS + HAL

时间:2018-10-18 22:22:43

标签: java spring-boot spring-restcontroller spring-hateoas

我按照spring.io Pivotal教程获得了带有MySQL DB的REST API,进展顺利。但是,我发现我无法配置或解决此问题。

当我使用内置功能从PagingAndSortingRepository中检索我的资源时,生成的REST被自动分页并封装有有用的HAL链接(_ links,self,search,linked Resources等)。 。我要使用它。

当我实现我的控制器以自定义PostMapping行为并引入健全性检查,验证等时,GetMapping停止工作。因此,我重新实现了一个利用我的服务层的GetMapping。

不幸的是,这样做破坏了以前提供的HATEOAS。

我想要的是能够自定义PostMapping,但保留GetMapping与默认值完全相同。如果可能的话,我希望避免自己编写,因为我知道框架可以提供。

有什么办法吗?

控制器:

@RestController
public class PartyMemberController {

    @Autowired
    PartyMemberService partyMemberService;

    @RequestMapping(method = RequestMethod.GET, value = "/partyMembers")
    public ResponseEntity<Iterable<PartyMember>> getAllPartyMembers() {
        Iterable<PartyMember> partyMemberList = partyMemberService.getAll();
        return new ResponseEntity<>(partyMemberList, HttpStatus.OK);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/partyMembers")
    public ResponseEntity<PartyMember> addEmployee(@Valid @RequestBody PartyMember partyMember) {
        if (partyMemberService.exists(partyMember)) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }

        partyMember = partyMemberService.save(partyMember);
        return new ResponseEntity<PartyMember>(partyMember, HttpStatus.CREATED);
    }
}

结果JSON

    [
      {
        "id": 2,
        "ward": {
          "id": 1,
          "name": "Mercier",
          "wardNumber": 42,
          "numberOfMembers": 3
        },
        "firstName": "Cindy",
        "lastName": "Tremblay",
        "partyMemberId": "12-1234-09876",
        "primaryPhone": "514-555-2323",
        "postalAddress": "1155 Robert-Bourassa, Montreal, Quebec, Canada, H3B3A7",
        "emailAddress": null,
        "secondaryPhone": null,
        "bestTimeToContact": null,
        "bestWayToContact": null,
        "membershipExpiry": null,
        "dateOfBirth": null,
        "donationEntries": [],
        "note": null
      },
      {
        "id": 3,
        "ward": {
          "id": 1,
          "name": "Mercier",
          "wardNumber": 42,
          "numberOfMembers": 3
        },
        "firstName": "Robert",
        "lastName": "Paulson",
        "partyMemberId": "12-1234-54321",
        "primaryPhone": "514-555-1212",
        "postalAddress": "440 Rue Saint-Pierre, App 5, Montreal, Quebec, Canada, H2Y2M5",
        "emailAddress": "rpaulson@papermillsoapcompany.com",
        "secondaryPhone": null,
        "bestTimeToContact": null,
        "bestWayToContact": null,
        "membershipExpiry": null,
        "dateOfBirth": null,
        "donationEntries": [],
        "note": null
      },
      {
        "id": 4,
        "ward": {
          "id": 1,
          "name": "Mercier",
          "wardNumber": 42,
          "numberOfMembers": 3
        },
        "firstName": "Richard",
        "lastName": "Schnobb",
        "partyMemberId": "12-4321-09876",
        "primaryPhone": "514-555-2323",
        "postalAddress": "440 Rue Saint-Pierre, App 5, Montreal, Quebec, Canada, H2Y2M5",
        "emailAddress": null,
        "secondaryPhone": null,
        "bestTimeToContact": null,
        "bestWayToContact": null,
        "membershipExpiry": null,
        "dateOfBirth": null,
        "donationEntries": [],
        "note": null
      }
    ]

默认JSON(请注意_embedded,_links等)。结果就是我想要的。

{
  "_embedded" : {
    "partyMembers" : [ {
      "firstName" : "Cindy",
      "lastName" : "Tremblay",
      "partyMemberId" : "12-1234-09876",
      "primaryPhone" : "514-555-2323",
      "postalAddress" : "1155 Robert-Bourassa, Montreal, Quebec, Canada, H3B3A7",
      "emailAddress" : null,
      "secondaryPhone" : null,
      "bestTimeToContact" : null,
      "bestWayToContact" : null,
      "membershipExpiry" : null,
      "dateOfBirth" : null,
      "donationEntries" : [ ],
      "note" : null,
      "_links" : {
        "self" : {
          "href" : "http://127.0.0.1:8080/partyMembers/2"
        },
        "partyMember" : {
          "href" : "http://127.0.0.1:8080/partyMembers/2"
        },
        "ward" : {
          "href" : "http://127.0.0.1:8080/partyMembers/2/ward"
        }
      }
    }, {
      "firstName" : "Robert",
      "lastName" : "Paulson",
      "partyMemberId" : "12-1234-54321",
      "primaryPhone" : "514-555-1212",
      "postalAddress" : "440 Rue Saint-Pierre, App 5, Montreal, Quebec, Canada, H2Y2M5",
      "emailAddress" : "rpaulson@papermillsoapcompany.com",
      "secondaryPhone" : null,
      "bestTimeToContact" : null,
      "bestWayToContact" : null,
      "membershipExpiry" : null,
      "dateOfBirth" : null,
      "donationEntries" : [ ],
      "note" : null,
      "_links" : {
        "self" : {
          "href" : "http://127.0.0.1:8080/partyMembers/3"
        },
        "partyMember" : {
          "href" : "http://127.0.0.1:8080/partyMembers/3"
        },
        "ward" : {
          "href" : "http://127.0.0.1:8080/partyMembers/3/ward"
        }
      }
    }, {
      "firstName" : "Richard",
      "lastName" : "Schnobb",
      "partyMemberId" : "12-4321-09876",
      "primaryPhone" : "514-555-2323",
      "postalAddress" : "440 Rue Saint-Pierre, App 5, Montreal, Quebec, Canada, H2Y2M5",
      "emailAddress" : null,
      "secondaryPhone" : null,
      "bestTimeToContact" : null,
      "bestWayToContact" : null,
      "membershipExpiry" : null,
      "dateOfBirth" : null,
      "donationEntries" : [ ],
      "note" : null,
      "_links" : {
        "self" : {
          "href" : "http://127.0.0.1:8080/partyMembers/4"
        },
        "partyMember" : {
          "href" : "http://127.0.0.1:8080/partyMembers/4"
        },
        "ward" : {
          "href" : "http://127.0.0.1:8080/partyMembers/4/ward"
        }
      }
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "http://127.0.0.1:8080/partyMembers{?page,size,sort}",
      "templated" : true
    },
    "profile" : {
      "href" : "http://127.0.0.1:8080/profile/partyMembers"
    },
    "search" : {
      "href" : "http://127.0.0.1:8080/partyMembers/search"
    }
  },
  "page" : {
    "size" : 20,
    "totalElements" : 3,
    "totalPages" : 1,
    "number" : 0
  }
}

3 个答案:

答案 0 :(得分:3)

要让Spring为您完成大部分工作,应该使用注释@RepositoryRestControllerdocs中的更多说明:

  

有时,您可能想为特定资源编写自定义处理程序。要利用Spring Data REST的设置,消息转换器,异常处理等功能,请使用@RepositoryRestController注释,而不是标准的Spring MVC @Controller或@RestController。带有@RepositoryRestController注释的控制器从RepositoryRestConfiguration.setBasePath中定义的API基本路径提供服务,所有其他RESTful端点(例如,/ api)都使用该API基本路径。


为了简化HATEOAS资源的生成(使用您提到的_links),可以利用ResourceAssemblerSupport

  

由于必须在多个位置使用从实体到资源类型的映射,因此有必要创建一个专门负责此操作的类。转换当然将包含非常自定义的步骤,但还将包含一些样板步骤。 (...)Spring Hateoas现在提供了ResourceAssemblerSupport基类,可帮助减少需要编写的代码量

答案 1 :(得分:2)

控制器上的返回类型不是Spring HATEOAS ResourceSupport类型,因此它将永远不会调用HAL序列化器。

您应该返回Resource<PartyMember>(对于单个项目)或Resources<Resource<PartyMember>>(对于列表)。结构化控制器以返回它们。

进行这些更改,然后将可重用ResourceAssembler<PartyMember, Resource<PartyMember>>的概念作为将在服务层中找到的PartyMember对象转换为用于呈现超媒体的Resource<PartyMember>对象的一种方式将非常有意义。

要了解基于REST的服务的这种演变,请查看本教程(我几个月前重写了该教程,以正确显示Spring HATEAOS的用法)=> https://spring.io/guides/tutorials/rest/

答案 2 :(得分:1)

您已经控制了ResponseEntity的控件,因此它不再为您自动构建。这意味着您必须使用LinkBuilder或ControllerLinkBuilder来构建与那些ResponseEntity自己关联的链接。

此处的文档和示例:https://docs.spring.io/spring-hateoas/docs/current/reference/html/#fundamentals.obtaining-links.entity-links

快速样本:

@Getter 
public class PersonResource extends ResourceSupport {
    private final Person person;
    public PersonResource(final Person person) {
        this.person = person;
        final long id = person.getId();
        add(linkTo(PersonController.class).withRel("people"));
        add(linkTo(methodOn(GymMembershipController.class).all(id)).withRel("memberships"));
        add(linkTo(methodOn(PersonController.class).get(id)).withSelfRel());
    }
}

最出色的案例:https://dzone.com/articles/applying-hateoas-to-a-rest-api-with-spring-boot