3
votes

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!

1

1 Answers

0
votes

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.