Elasticsearch Java客户端JacksonMap器污染Spring JacksonMap器

fykwrbwg  于 2022-12-26  发布在  ElasticSearch
关注(0)|答案(1)|浏览(151)

我正在将我的Sping Boot 项目更新到3.0.0版本,其中一个重要的依赖项是Spring Data Elastic Repository,我包含了启动器依赖项:

implementation("org.springframework.boot:spring-boot-starter-data-elasticsearch")

更新依赖项后,我的单元测试失败了,因为web控制器不再提供空值。我尝试使用属性包含配置来更改行为:

spring:
  jackson:
    default-property-inclusion: always

这没有帮助。我调试了代码组,似乎新的Elastic Java Client有自己的JacksonMapper配置,它将全局配置设置为'NON_NULL'。

package co.elastic.clients.json.jackson;

...

public class JacksonJsonpMapper extends JsonpMapperBase {

    private final JacksonJsonProvider provider;
    private final ObjectMapper objectMapper;

   ...

    public JacksonJsonpMapper(ObjectMapper objectMapper) {
        this(
            objectMapper
                .configure(SerializationFeature.INDENT_OUTPUT, false)
                .setSerializationInclusion(JsonInclude.Include.NON_NULL),
            // Creating the json factory from the mapper ensures it will be returned by JsonParser.getCodec()
            new JacksonJsonProvider(objectMapper.getFactory())
        );
    }

...

有人知道如何解决这个问题吗?

mbskvtky

mbskvtky1#

我找到了这个问题的解决方案。Sping Boot 有一个用于弹性JacksonMap器的自动配置。这个自动配置使用与Web控制器相同的ObjectMapper:
´´´

package org.springframework.boot.autoconfigure.elasticsearch;

...

/**
 * Configurations for import into {@link ElasticsearchClientAutoConfiguration}.
 *
 * @author Andy Wilkinson
 */
class ElasticsearchClientConfigurations {

@ConditionalOnMissingBean(JsonpMapper.class)
@ConditionalOnBean(ObjectMapper.class)
@Configuration(proxyBeanMethods = false)
static class JacksonJsonpMapperConfiguration {

    @Bean
    JacksonJsonpMapper jacksonJsonpMapper(ObjectMapper objectMapper) {
        return new JacksonJsonpMapper(objectMapper);
    }

}

...
´´´
可以覆盖此Bean以复制ObjectMapper示例并为弹性客户端创建自己的ObjectMapper:
´´´

@Configuration
internal class CustomJacksonJsonpMapperConfiguration {
@Bean
fun jacksonJsonpMapper(objectMapper: ObjectMapper): JacksonJsonpMapper {

    return JacksonJsonpMapper(objectMapper.copy())
}
}

´´´

相关问题