spring-bootspring-dataspring-data-mongodb

How to customize MappingMongoConverter (setMapKeyDotReplacement) in Spring-Boot without breaking the auto-configuration?


How could I customize the MappingMongoConverter within my Spring-Boot-Application (1.3.2.RELEASE) without changing any of the mongo-stuff which is autoconfigured by spring-data?

My current solution is:

@Configuration
public class MongoConfig {

  @Autowired
  private MongoDbFactory mongoFactory;

  @Autowired
  private MongoMappingContext mongoMappingContext;

  @Bean
  public MappingMongoConverter mongoConverter() throws Exception {
    DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoFactory);
    MappingMongoConverter mongoConverter = new MappingMongoConverter(dbRefResolver, mongoMappingContext);
    //this is my customization
    mongoConverter.setMapKeyDotReplacement("_");
    mongoConverter.afterPropertiesSet();
    return mongoConverter;
  }
}

Is this the right way or do I break some stuff with this?
Or is there even a more simple way to set the mapKeyDotReplacement?


Solution

  • That's the right way to do it. The auto-configured MappingMongoConverter is annotated with @ConditionalOnMissingBean(MongoConverter.class), so adding your own MappingMongoConverter bean will cause the auto-configuration to back off in favour of your custom converter.

    One minor correction: there's no need for you to call mongoConverter.afterPropertiesSet(). The container will call that for you.