spring hateoas 1.0改动

SpringHATEOAS的1.0版本中,Resource被替换为EntityModel,Resources变为CollectionModel,ResourceSupport改名为RepresentationModel。尽管用法位置相似,但类名已更新。TacoModelAssembler继承自RepresentationModelAssemblerSupport,方法和功能基本保持一致。示例展示了如何在新版本中创建和使用这些模型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

spring hateoas 1.0

前言

因为在看spring实战第五版敲代码时候发现改组件已经更新,书中没改,旧方法已在新版本弃用

Resource

改为EntityModel

变化

和原来用法位置一样,改了名而已

在这里插入图片描述

Resources

改为CollectionModel

变化

和原来用法位置一样,改了名而已

在这里插入图片描述

ResourceSupport

改为RepresentationModel

变化

使用方法和原来无差别

public class TacoModel extends RepresentationModel<TacoModel> {
    @Getter
    private final String name;

    @Getter
    private final Date createAt;

    @Getter
    private final List<Ingredient> ingredients;

    public TacoModel(Taco taco) {
        this.name = taco.getName();
        this.createAt = taco.getCreatedAt();
        this.ingredients = taco.getIngredients();
    }
}

ResourceAssemblerSuppor

改为RepresentationModelAssemblerSuppor

变化

使用起来和原先没什么太大差异,只是映射名称和方法名变了

public class TacoModelAssembler extends RepresentationModelAssemblerSupport<Taco, TacoModel> {
    public TacoModelAssembler() {
        super(DesignTacoApiController.class, TacoModel.class);
    }

    @Override
    public TacoModel toModel(Taco taco) {
        return createModelWithId(taco.getId(), taco);
    }

    @Override
    protected TacoModel instantiateModel(Taco taco) {
        return new TacoModel(taco);
    }
}
public CollectionModel<TacoModel> recentTacos() {
    PageRequest page = PageRequest.of(0, 12, Sort.by("createdAt").descending());
    List<Taco> tacos = tacoRepository.findAll(page).getContent();

    CollectionModel<TacoModel> recentCollectionModel = new TacoModelAssembler().toCollectionModel(tacos);

    recentCollectionModel.add(
            linkTo(methodOn(DesignTacoApiController.class).recentTacos())
                    .withRel("recents")
    );
    return recentCollectionModel;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值