Spring not using mongo custom converters

2020-02-12 08:09发布

问题:

I have been trying to register my own write custom converters to change the default ID value. But it never actually calls. Here is my Custom Converter

public class EventKeyConverter implements Converter<Event,DBObject> {

    @Override
    public DBObject convert(Event object) {
        DBObject dbObject = DBObjectTransformer.toDBObject(object);
        dbObject.put("_id", KeyGenerator.getRandomKey());
        return dbObject;
    }

}

here is the place that I did register customer converter

@Override
@Bean
public CustomConversions customConversions() {
    List<Converter<?, ?>> converters = new ArrayList<Converter<?, ?>>();
    converters.add(new EventKeyConverter());
    return new CustomConversions(converters);
}

@Override
@Bean
public MappingMongoConverter mappingMongoConverter() throws Exception {
    MappingMongoConverter converter = new MappingMongoConverter(
            eventsMongoDbFactory(), mongoMappingContext());
    converter.setCustomConversions(customConversions());
    return converter;
}

@Bean
public MongoTemplate eventsMongoTemplate() throws Exception {
    final MongoTemplate template = new MongoTemplate(
            eventsMongoDbFactory(), mappingMongoConverter());
    template.setWriteResultChecking(WriteResultChecking.EXCEPTION);

    return template;
}

When I'm saving some objects this converter never gets called.


Edit 1 : I need to change the default object Id into some custom Id (UUID + random key) in all repositories. That why I tried to use mongo converter.

Edit 2 : Just found the issue. Change @Configuration to @Component in class that contains customConversion() and it works fine. But still wondering what is happened here ?

回答1:

@Configuration defines a Spring context fragment that contains methods that if annotated with @Bean return new beans and put them in the context.

@Component is a way of saying "this Pojo is a Spring bean". You then need a @ComponentScan annotation or XML equivalent to scan packages for @Component annotated beans.

So in your case, you created the converter fine, but it wasn't registered as a Spring bean until you added the @Component, so it didn't work initially.