【问题标题】:Using @JsonView with Spring Hateoas将 @JsonView 与 Spring Hateoas 一起使用
【发布时间】:2017-04-14 04:20:57
【问题描述】:

如果我在 POJO 和 Spring 的控制器上使用 @JsonView,我的 HATEOAS 链接将被隐藏。我可以理解为什么会发生这种情况,因为 _links 属性没有使用正确的视图类进行注释,但这不是我在这种情况下需要的行为。无论是否使用视图类,有没有办法始终包含 _links 属性?

我的 POJO 看起来像:

@Entity(name = "groups")
@SequenceGenerator(name = "groups_groupid_seq", sequenceName = "groups_groupid_seq")
public class Group extends ResourceSupport {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "groups_groupid_seq")
    @JsonView(Views.Summary.class)
    private long groupID;

    @JsonView(Views.Full.class)
    private String name;

    /*
        Getters & setters ...
     */
}

我的控制器看起来像:

@RestController
@RequestMapping(path = "/group")
@ExposesResourceFor(Group.class)
public class GroupApiController {
    @JsonView(Views.Summary.class)
    @RequestMapping(path = "/", method = RequestMethod.GET)
    public Iterable getPermittedGroups(
            Authentication authentication) {
        // load groups...
    }
}

我的 HATEOAS 配置:

@Configuration
@EnableAspectJAutoProxy
@EnableEntityLinks
@EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)
public class HateoasConfig {
    //
}

我不必使用@JsonView,所以我很乐意使用替代方法。但我确实需要能够从不同的控制器方法返回同一类的不同视图,否则我可以使用@JsonIgnore

【问题讨论】:

    标签: java spring spring-boot spring-hateoas


    【解决方案1】:

    有没有办法总是包含 _links 属性,不管 是否使用视图类?

    使用 Spring Boot
    设置 spring jackson mapper 配置 spring.jackson.mapper.default-view-inclusion=true 在您的 application.properties 中

    使用 Spring @Configuration 类
    这个话题在"Configuring Object Mapper in Spring"中有很好的介绍

    但是,目前特别是 HATEOAS 存在一些问题,导致它无法正常工作。尤其是开票"Support for HATEOAS-Links in Json-Views"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-28
      • 2013-07-20
      • 2020-02-12
      • 2019-08-16
      • 2013-10-31
      相关资源
      最近更新 更多