超媒体作为应用状态引擎(Hypermedia as the Engine of Application State,HATEOAS) 是一种创建自我描述API消费的方式
API所返回的资源中会包含相关资源的链接,客户端只需要了解最少的API URL信息就能导航整个API。这种方式能够掌握API所
提供的资源之间的关系,客户端能够基于API的URL中所发现的关系对它们进行遍历。
带超级链接风格的HATEOAS被称为HAL(超文本应用语言,Hypertext Application Language)。这是一种在JSON中嵌入超链接
的简单通用格式。
在API项目中启用超媒体功能,需要在构建文件pom.xml文件中添加如下依赖:
<!-- 启用超媒体功能-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
package tacos.web.api;
import lombok.Getter;
import org.springframework.hateoas.CollectionModel;
import org.springframework.hateoas.RepresentationModel;
import org.springframework.hateoas.server.core.Relation;
import tacos.Taco;
import java.util.Date;
/*
*taco资源
*/
@Relation(value = "taco",collectionRelation = "tacos")//声明生成Json时的对象名称
public class TacoResource extends RepresentationModel<TacoResource> {
private static final IngredientResourceAssembler ingredientAssembler=new IngredientResourceAssembler(IngredientController.class,IngredientResource.class);
@Getter
private final String name;
@Getter
private final Date createdAt;
@Getter
private final CollectionModel<IngredientResource> ingredients;
public TacoResource(Taco taco){
this.name=taco.getName();
this.createdAt=taco.getCreatedAt();
this.ingredients= ingredientAssembler.toCollectionModel(taco.getIngredients());
}
}
package tacos.web.api;
import org.springframework.hateoas.server.mvc.RepresentationModelAssemblerSupport;
import tacos.Taco;
/*
*资源装配器,装配taco资源
*/
public class TacoResourceAssembler extends RepresentationModelAssemblerSupport<Taco,TacoResource> {
public TacoResourceAssembler() {
super(DesignTacoApiController.class, TacoResource.class);
}
public TacoResourceAssembler(Class<DesignTacoApiController> designTacoApiControllerClass, Class<TacoResource> tacoResourceClass) {
super(designTacoApiControllerClass,tacoResourceClass);
}
@Override
protected TacoResource instantiateModel(Taco entity) {
return new TacoResource(entity);
}
@Override
public TacoResource toModel(Taco entity) {
return createModelWithId(entity.getId(),entity);
}
}
package tacos.web.api;
import lombok.Getter;
import org.springframework.hateoas.RepresentationModel;
import org.springframework.hateoas.server.core.Relation;
import tacos.Ingredient;
/*
*Ingredient资源
*/
@Relation(value = "ingredient",collectionRelation = "ingredients")
public class IngredientResource extends RepresentationModel<IngredientResource> {
@Getter
private final String name;
@Getter
private final Ingredient.Type type;
public IngredientResource(Ingredient entity){
this.name=entity.getName();
this.type=entity.getType();
}
}
package tacos.web.api;
import org.springframework.hateoas.server.mvc.RepresentationModelAssemblerSupport;
import tacos.Ingredient;
/*
*装配资源
*/
public class IngredientResourceAssembler extends RepresentationModelAssemblerSupport<Ingredient,IngredientResource> {
public IngredientResourceAssembler(Class<?> controllerClass, Class<IngredientResource> resourceType) {
super(controllerClass, resourceType);
}
@Override
protected IngredientResource instantiateModel(Ingredient entity) {
return new IngredientResource(entity);
}
@Override
public IngredientResource toModel(Ingredient entity) {
return createModelWithId(entity.getId(),entity);
}
}
package tacos.web.api;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.hateoas.CollectionModel;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import tacos.Order;
import tacos.Taco;
import tacos.data.OrderRepository;
import tacos.data.TacoRepository;
import java.util.List;
import java.util.Optional;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;
@RestController//控件器中的所有处理器方法的返回值都要直接写入响应主体中,而不是将值放入模型Model中并传递给视图.
@RequestMapping(path = "/design",produces = {"application/json"})//指定API生成Json数据
@CrossOrigin(origins = "*")//允许跨域访问,允许来自任何域的客户端消费该API
public class DesignTacoApiController {
private TacoRepository tacoRepo;
private OrderRepository orderRepo;
public DesignTacoApiController(TacoRepository tacoRepo, OrderRepository orderRepo) {
this.tacoRepo = tacoRepo;
this.orderRepo = orderRepo;
}
@GetMapping("/recent")
public CollectionModel<TacoResource> recentTacos(){
return getTacoResources();
}
//返回带有状态包装的实例
@GetMapping("/recent2")
public ResponseEntity<CollectionModel<TacoResource>> recentTacos2() {
return new ResponseEntity<>(getTacoResources(), HttpStatus.OK);
}
private CollectionModel<TacoResource> getTacoResources() {
PageRequest page=PageRequest.of(0,12, Sort.by("createdAt").descending());
List<Taco> tacos=tacoRepo.findAll(page).getContent();
CollectionModel<TacoResource> recentResources=new TacoResourceAssembler(DesignTacoApiController.class,TacoResource.class)
.toCollectionModel(tacos);
recentResources.add(linkTo(methodOn(DesignTacoApiController.class).recentTacos()).withRel("recents"));
return recentResources;
}
}
注意:低版本中所用到的类
ResourceSupport
就是现在RepresentationModel
Resource
就是现在EntityModel
Resources
就是现在CollectionModel
PagedResources
就是现在PagedModel