问题
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
回答1:
Did you annotate your MongoConfig
class with @Configuration
?
Your class MongoConfig need to be managed by the Spring BeanFactory to get callback afterPropertiesSet()
( where conversions.registerConvertersIn(conversionService)
is originally called ) automatically called
If you don't annotate you configuration bean you need to call afterPropertiesSet()
yourself
回答2:
Nothing worked for me but this.While setting up mongo template we need to tell to mongo db use the custom conversion.
@Bean
public MongoTemplate mongoTemplate() throws Exception {
MongoTemplate mongoTemplate = new MongoTemplate(mongo(), mongoDatabase);
MappingMongoConverter mongoMapping = (MappingMongoConverter) mongoTemplate.getConverter();
mongoMapping.setCustomConversions(customConversions()); // tell mongodb to use the custom converters
mongoMapping.afterPropertiesSet();
return mongoTemplate;
}
Follow this link for more details : http://ufasoli.blogspot.in/2017/06/custom-converter-for-mongodb-and-spring.html
来源:https://stackoverflow.com/questions/34212545/setup-custom-converters-in-spring-data-mongo