【问题标题】:Implementing Spring HATEOAS linkbuilding实现 Spring HATEOAS 链接构建
【发布时间】:2016-04-27 11:52:12
【问题描述】:

我不明白我需要添加什么才能使我的程序成为 HATEOAS。我有 Account.java、Post.java、Controllersrepositories。从一些指南中,他们添加了 AccountResource 和 PostResource,他们在这些类中构建链接。 AccountResource 和 Account 有什么区别?我需要两者吗?如果是这样,我是否为每个普通类创建一个资源类?我试过这样做,但它根本没有用。我不知道我在做什么了:(。我需要一些帮助来了解如何从普通 REST 迁移到 HATEOAS。我需要添加哪些类?

public class Account {

//Account ID
@Id private String userId;

//General info
protected String firstName;
protected String lastName;
protected String username;
protected String email;
protected String password;
protected String birthDate;
protected String activities;
protected String uri;
private Set<Post> posts = new HashSet<>();
List<Account> friends = new ArrayList<Account>();

//Getter, constructor...



@RestController
public class AccountController {    

@Autowired
private AccountRepository accountRepository;

//Create account 
@RequestMapping(value="/accounts", method = RequestMethod.POST) 
public ResponseEntity<?> accountInsert(@RequestBody Account account) {

    account = new Account(account.getUri(), account.getUsername(), account.getFirstName(), account.getLastName(), account.getEmail(), account.getPassword(), account.getBirthDate(), account.getActivities(), account.getFriends());
    accountRepository.save(account);
    HttpHeaders httpHeaders = new HttpHeaders();
    Link forOneAccount = new AccountResource(account).getLink("self");
    httpHeaders.setLocation(URI.create(forOneAccount.getHref()));

    return new ResponseEntity<>(null, httpHeaders, HttpStatus.CREATED);
}



public class AccountResource extends ResourceSupport {

private Account account;

public AccountResource(Account account) {
    String username = account.getUsername();
    this.account = account;
    this.add(new Link(account.getUri(), "account-uri"));
    this.add(linkTo(AccountController.class, username).withRel("accounts"));
    this.add(linkTo(methodOn(AccountController.class, username).getUniqueAccount(account.getUserId())).withSelfRel());
}

public AccountResource() {

}

public Account getAccount() {
    return account;
}
}

【问题讨论】:

    标签: java spring rest hateoas


    【解决方案1】:

    AccountPost 等是您的域实体,而 *Resource 是您的 API 向外部世界公开的表示形式。

    例如,域实体可能是 JPA 实体,包含它们的持久性和与其他实体的关系所需的所有元数据。 即使它们不是 JPA 实体,它们也是应用程序业务逻辑使用的内部表示。

    Resources 包含 JSON 序列化/反序列化的信息,不直接引用其他资源。

    查看此示例项目https://github.com/opencredo/spring-hateoas-sample 和相关博客文章:Implementing HAL hypermedia REST API using Spring HATEOAS

    它实现了一个简单但不那么简单的库 API,具有 Book - Author - Publisher 域。

    【讨论】:

      猜你喜欢
      • 2019-01-03
      • 1970-01-01
      • 2016-04-14
      • 2016-05-23
      • 2015-04-18
      • 2023-03-28
      • 2018-02-25
      • 1970-01-01
      • 2014-09-21
      相关资源
      最近更新 更多