移除Spring Data REST投影中的自链接模板化
解决HATEOAS模板化链接生成非模板化常规链接的非取巧方案
好的,针对你遇到的这个问题,我给你几个基于Spring HATEOAS原生机制的正规实现方式,完全不需要依赖前端HATEOAS客户端,也不属于“取巧”的歪招:
方法1:手动构建非模板化Self链接
在你的Patient资源装配器(ResourceAssembler)中,直接通过Link.of()方法生成固定的非模板化链接,替代默认的模板化链接。这种方式完全由你控制链接格式,最直接可靠:
@Override public PatientModel toModel(Patient entity) { PatientModel model = instantiateModel(entity); // 直接拼接生成不带模板参数的self链接 String selfHref = "http://localhost:8090/api/patients/" + entity.getId(); // 添加非模板化的self链接 model.add(Link.of(selfHref, LinkRelation.SELF).withTemplated(false)); return model; }
方法2:通过Spring Data REST配置全局或局部调整
如果你使用的是Spring Data REST,默认的模板化链接是框架自动添加的,可以通过配置或自定义处理器来修改:
全局关闭模板化链接
在application.properties或application.yml中添加配置,全局禁用模板化链接:
spring.data.rest.use-templated-links=false
针对单个实体调整链接
如果只想修改Patient实体的链接,自定义一个ResourceProcessor来替换模板化链接:
@Component public class PatientModelProcessor implements ResourceProcessor<PatientModel> { @Override public PatientModel process(PatientModel model) { // 获取原有的模板化self链接 Link templatedSelfLink = model.getLink(LinkRelation.SELF) .orElseThrow(() -> new IllegalStateException("Self link not found")); // 移除模板参数,生成非模板化链接 String cleanHref = templatedSelfLink.getHref().replace("{?projection}", ""); // 替换为非模板化链接 Link nonTemplatedSelfLink = templatedSelfLink.withHref(cleanHref).withTemplated(false); model.removeLink(LinkRelation.SELF); model.add(nonTemplatedSelfLink); return model; } }
方法3:使用WebMvcLinkBuilder构建规范的非模板化链接
利用Spring HATEOAS的WebMvcLinkBuilder,通过控制器方法映射生成链接,这种方式更符合RESTful规范,也能避免硬编码URL:
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; @Override public PatientModel toModel(Patient entity) { PatientModel model = instantiateModel(entity); // 通过控制器方法生成非模板化的self链接 Link selfLink = linkTo(methodOn(PatientController.class).getPatient(entity.getId())) .withSelfRel() .withTemplated(false); model.add(selfLink); return model; }
以上几种方法都是基于Spring HATEOAS的原生API或配置实现,完全属于正规的解决方案,没有依赖任何非常规的“取巧”手段,你可以根据自己的项目架构选择最适合的方式。
内容的提问来源于stack exchange,提问作者kidustiliksew
相关产品推荐
相关产品推荐

