实现Spring HATEOAS链接构建

时间:2016-04-27 11:52:12

标签: java spring rest hateoas

我不明白我需要添加什么来让我的程序成为HATEOAS。我有帐户 .java,发布 .java,控制器存储库。从一些指南中,他们添加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;
}
}

1 个答案:

答案 0 :(得分:0)

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域。