Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 525
Mike Boddin Avatar asked Feb 24 '16 09:02

Mike Boddin


2 Answers

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.

like image 121
Andy Wilkinson Avatar answered Nov 20 '22 11:11

Andy Wilkinson


I have run into this issue in the latest version of spring boot. Your approach did not work for me or the accepted answer...my boot app seemed to ignore my custom mapping converter.

So what I did in the config class I autowired in the MappingMongoConverter that boot uses and then set the setMapKeyDotReplacement on that.

@Autowired
private MappingMongoConverter mongoConverter;

// Converts . into a mongo friendly char
@PostConstruct
public void setUpMongoEscapeCharacterConversion() {
    mongoConverter.setMapKeyDotReplacement("_");
}
like image 10
David Billings Avatar answered Nov 20 '22 12:11

David Billings