Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setup custom converters in Spring Data Mongo

We are trying to setup our own Converters for Spring Data Mongo and having problems with it.

Seems like Spring never calls for registerConvertersIn on CustomConversions and thus our custom converters added through overriden AbstractMongoConfiguration#customConversions never become part of conversion.

We are using Spring Data Mongo 1.6.3, but it seems it could be a problem for 1.8.0 too (I've checked calls to CustomConversions#registerConvertersIn and found none.)

I was able to fix this problem by calling CustomConversions#registerConvertersIn in custom MappingMongoConverter like this:

class MongoConfig extends AbstractMongoConfiguration {
    @Bean
    @Override
    public MappingMongoConverter mappingMongoConverter() throws Exception {
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory());
        MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mongoMappingContext()) {
            @Override
            public void setCustomConversions(CustomConversions conversions) {
                super.setCustomConversions(conversions);
                conversions.registerConvertersIn(conversionService);
            }

        };
        converter.setCustomConversions(customConversions());
        return converter;
    }
}

Is that a bug or we are doing something wrong?

Found another work around: https://stackoverflow.com/a/14369998/4567261

like image 851
Konstantin Fedorov Avatar asked Dec 10 '15 22:12

Konstantin Fedorov


1 Answers

In Spring Boot 2.x it's as simple as creating a registration bean that registers all of your converters:

@Configuration
public class Converters {

  @Bean
  public MongoCustomConversions mongoCustomConversions() {

    return new MongoCustomConversions(
        Arrays.asList(
            new MyClassToBytesConverter(),
            new BytesToMyClassConverter()));
  }
}

Then create your converter classes:

@WritingConverter
public class MyClassToBytesConverter implements Converter<MyClass, Binary> {

  @Override
  public Binary convert(MyClasssource) {
  // your code
  }
}
@ReadingConverter
public class BytesToMyClassConverter implements Converter<Binary, MyClass> {

  @Override
  public MyClass convert(Binary source) {
  /// your code
  }
}
like image 161
Andy Brown Avatar answered Sep 28 '22 16:09

Andy Brown