Spring HATEOAS不遵守资源链接的默认包含属性

时间:2018-12-11 14:16:26

标签: java spring spring-mvc spring-boot spring-hateoas

我遇到的问题类似于this question中提出的问题,但是采用了建议的解决方案

spring.jackson.default-property-inclusion=NON_NULL不会阻止HATEOAS渲染具有空属性的链接。这是我的控制器声明

@RestController
@ExposesResourceFor(Customer.class)
public class CustomerController {
  // controller methods here
}

和网络配置类

@Configuration
@EnableSpringDataWebSupport
@EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)
public class DataApiWebConfiguration extends WebMvcConfigurationSupport {
  // config here
}

在返回资源的Controller get方法中,我声明了映射,如下所示

@GetMapping(value = "/customers/{id}", produces = MediaTypes.HAL_JSON_VALUE)

然后返回Resource

Optinal<Customer> customer = customerRepository.findById(id);
return customer.map(customerResourceAssembler::toResource).map(ResponseEntity::ok)
                            .orElse(ResponseEntity.notFound().build());

CustomerResourceAssembler扩展了SimpleIdentifiableResourceAssembler,如this spring-hateaos example所示。

但是在响应正文中,我仍然看到使用null属性呈现的链接

"links": [
            {
                "rel": "self",
                "href": "http://localhost:8080/customers/11",
                "hreflang": null,
                "media": null,
                "title": null,
                "type": null,
                "deprecation": null
            }
]

这看起来不像HATEOAS响应,就像在示例中,我在JSON中看到_links而不是links

1 个答案:

答案 0 :(得分:0)

问题出在我的配置类中,我以错误的方式注册了Hibernate5Module,删除了这些行

quill.root.innerHTML = postContent;

并简单地添加了一个豆

@Bean
    public MappingJackson2HttpMessageConverter customJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new HibernateAwareObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        jsonConverter.setObjectMapper(objectMapper);
        return jsonConverter;
    }

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(customJackson2HttpMessageConverter());
    super.addDefaultHttpMessageConverters(converters);
}
固定输出的

@Bean
public Module hibernate5Module() {
    return new Hibernate5Module();
}