简体   繁体   中英

mongoDb and spring data custom converter for enum field

I have a simple Java class called Metric which has two fields: MetricType and value:

public class Metric {
    MetricType type;
    int value;
}

enum MetricType {
    SPACE, CPU, UNKNOWN
}

When reading the metrics from mongo I want the a custom convertor for MetricType which will convert anything which is not mapped to enum to UNKNOWN.

My repository is a simple repository :

public interface MetricRepository extends MongoRepository<Metric, 
String> {}

I am using spring-boot-starter-data-mongodb version 1.5.9

what I tried doing is creating a Converter from string to MetricType

@ReadingConverter
public class StringToMetricTypeConverter implements Converter<String, MetricType> {

    @Override
    public MetricType convert(String dbData) {
         try {
             return MetricType.valueOf(dbData);
         }
        catch (IllegalArgumentException e) {
            return MetricType.UNKNOWN;
        }
     }
 }

and in the mongoConfig file adding:

@Bean
public MongoTemplate mongoTemplate() throws Exception {
    MongoTemplate mongoTemplate = new MongoTemplate(mongo(), getDatabaseName());
    MappingMongoConverter mongoMapping = (MappingMongoConverter) mongoTemplate.getConverter();
    mongoMapping.setCustomConversions(customConversions()); 
    mongoMapping.afterPropertiesSet();
    return mongoTemplate;
}

@Bean
public CustomConversions customConversions() {
    return new CustomConversions(Arrays.asList(new StringToMetricTypeConverter()));
}

I do see the converter is registered in the mongoTemplate but the converter is not being called... what am I missing here?

thanks!

You could try to use MongoCustomConversions instead of org.springframework.data.convert. CustomConversions . MongoCustomConversions is a subclass of CustomConversions

But the ideal would be not to require any conversions at all or that the converter could be configurable inside the enums.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM