Spring-boot: register mongodb custom converter

Viewed 6901

I'm using this dependency into my spring bott service:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

I've created a custom converter:

import org.springframework.core.convert.converter.Converter;

@Component
public class ReferenceWriterConverter implements Converter<Reference, DBObject> {
    @Override
    public DBObject convert(Reference reference) {
        DBObject dbObject = new BasicDBObject();
        //...
        return dbObject;
    }
}

I'm trying to figure out how to "register" this converter. However, diving over there I don't quite figure out whether I need to use a CustomConvertions class or MappingMongoConverter.

How would I need to "register" my custom converter into my spring boot service?

Any ideas?

1 Answers

You need to override the customConversions of mongodb, like so:

@Configuration
public class MongoConfig {

    @Bean
    public MongoCustomConversions customConversions(){
        List<Converter<?,?>> converters = new ArrayList<>();
        converters.add(ReferenceWriterConverter.INSTANCE);
        return new MongoCustomConversions(converters);
    }

    @WritingConverter
    enum ReferenceWriterConverter implements Converter<Reference, DBObject> {

        INSTANCE;

        @Override
        public String convert(Reference reference) {
            //do stuff
        }
    }
}

Of course, you can also declare the converter in your separate class like above and just autowire it into the configuration.

Related