我使用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默认相同的行为?
不幸的是,这并没有帮助。 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
好吧,现在我明白你的问题。 –
这对于Spring Data Rest存储库端点是正确的,但不能独立使用ObjectMapper(例如控制器中的自动装配)。默认的ObjectMapper(当'RepositoryRestMvcConfiguration'未扩展时通过自动装配可用)呈现嵌套实体,即使没有预测也是如此。 只要我为了配置的目的而扩展'RepositoryRestMvcConfiguration',当在独立模式下使用objectMapper/halObjectMapper就不再呈现嵌套实体。 – Michal