Spring Boot & Mongo: custom MappingMongoConverter doesn't work during DotReplacement

1.4k views Asked by At

I need to achive dotReplacementKey

I'm using MongoDB with such config:

@Configuration
public class MongoTemplateConfig {

@Value("${adserver_mongo_connection_string}")
private String databaseConnectionString;

@Bean
public MongoDbFactory mongoDbFactory() throws UnknownHostException {

    MongoClientURI uri = new MongoClientURI(databaseConnectionString.trim());
    return new SimpleMongoDbFactory(uri);
}

@Bean
public MongoTemplate mongoTemplate() throws UnknownHostException {
    return new MongoTemplate(mongoDbFactory());
}

@Bean
public MappingMongoConverter mongoConverter(MongoDbFactory mongoFactory, MongoMappingContext mongoMappingContext) throws Exception {
    DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoFactory);
    MappingMongoConverter mongoConverter = new MappingMongoConverter(dbRefResolver, mongoMappingContext);
    mongoConverter.setMapKeyDotReplacement(".");

    return mongoConverter;
}
}

I'm doing upsert as follows: mongoTemplate.bulkOps(...).upsert(...)

but during runtime via debug I found out that different MappingMongoConverter is used rather then this that was configured as a @Bean

btw, if @Inject wherever MappingMongoConverter I get proper bean from config with keyDotReplacement="." but looks like Spring Boot uses another one under the hood

P.S. I have seen this question without correct answer, but tried with mongoConverter.afterPropertiesSet() and obviously it doesn't work as well

1

There are 1 answers

1
Roman  Hrytsyshyn On

It's a bit ridiculous but the point is that we should pass this custom mappingMongoConverter into MongoTemplate initialization :

@Bean
public MongoTemplate mongoTemplate(MappingMongoConverter mappingMongoConverter) throws UnknownHostException {
    return new MongoTemplate(mongoDbFactory(), mappingMongoConverter);
}