2016-12-15 68 views
2

我使用RepositoryRestMvcConfiguration为休息库行为的微调:RepositoryRestMvcConfiguration的ObjectMapper与Spring Boot默认的ObjectMapper?

@Configuration 
public class WebConfig extends RepositoryRestMvcConfiguration { 
    @Override 
    protected void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) { 
     config.setReturnBodyOnCreate(true); 
} 

缺点是扩展的类带来了自己的ObjectMapper豆,造成conficts描述here。推荐的解决方法是使用扩展类将ObjectMapper bean标记为@Primary,但在对序列化嵌套实体时,RepositoryRestMvcConfiguration的bean具有不同的行为。

假设以下enitites:

@Entity class Parent { 
    @Id Long id; 
    @OneToMany @JsonManagedReference List<Child> children; 
    // usual getters and setters for fields... 
} 

@Entity class Child { 
    @Id Long id; 
    @ManyToOne @JsonBackReference Parent parent; 
    @ManyToOne @JsonBackReference School school; 
    public getSchooldId() { return school.getId(); } 
    // usual getters and setters for fields... 
} 

@Entity class School { 
    @Id Long id; 
    @OneToMany @JsonManagedReference List<Child> children; 
    // usual getters and setters for fields... 
} 

使用默认的春天引导ObjectMapper给出了预期的结果(嵌套实体渲染):

{"id": 1, "children":[{"id":2, "schoolId":7},{"id":3, "schooldId":8}]} 

但是从RepositoryRestMvcConfiguration的ObjectMapper忽略子实体:

{"id": 1} 

什么是正确配置RepositoryRestMvcConfiguration ObjectMapper以实现与Spring Boot默认相同的行为?

回答

0

RepositoryRestMvcConfiguration创建两个objectMapper对象。

  1. objectMapper for internal framework use。
  2. halObjectMapper负责渲染集合Resources和链接。

您可以尝试使用预选赛自动装配的objectMapper以达到预期的效果:

@Qualifier('_halObjectMapper') 

编辑:对于渲染协会/嵌套属性

春数据休息不会呈现默认关联(reference),因为它们在HATEOAS规范(您的json的_link部分)下可用。 如果你想渲染关联,你只需要使用预测

这个人有几个属性:id是主键,firstName和lastName是数据的属性,地址是另一个域对象的链接

@Entity 
public class Person { 

    @Id @GeneratedValue 
    private Long id; 
    private String firstName, lastName; 

    @OneToOne 
    private Address address; 
    … 
} 

将呈现:

{ 
    "firstName" : "Frodo", 
    "lastName" : "Baggins", 
    "_links" : { 
    "self" : { 
     "href" : "http://localhost:8080/persons/1" 
    }, 
    "address" : { 
     "href" : "http://localhost:8080/persons/1/address" 
    } 
    } 
    } 

默认情况下,Spring Data REST将导出包含所有属性的域对象。 firstName和lastName将作为它们的普通数据对象导出。关于地址属性有两个选项。一种选择是为Address定义一个存储库。

还有另外一条路线。如果地址域对象没有自己的存储库定义,则Spring Data REST将在Person资源内嵌入数据字段。

+0

不幸的是,这并没有帮助。 1)objectMapper也'@由其他弹簧引导代码Autowired'(例如构造在org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration) 2)halObjectMapper可以通过使用 \t'@Override @Bean制成默认@Primary \t public ObjectMapper objectMapper(){ \t \t return super.halObjectMapper(); \t}' 但它给出了与其他objectMapper相同的结果 - 嵌套实体不呈现给JSON – Michal

+0

好吧,现在我明白你的问题。 –

+0

这对于Spring Data Rest存储库端点是正确的,但不能独立使用ObjectMapper(例如控制器中的自动装配)。默认的ObjectMapper(当'RepositoryRestMvcConfiguration'未扩展时通过自动装配可用)呈现嵌套实体,即使没有预测也是如此。 只要我为了配置的目的而扩展'RepositoryRestMvcConfiguration',当在独立模式下使用objectMapper/halObjectMapper就不再呈现嵌套实体。 – Michal