[英]mongoDb and spring data custom converter for enum field
I have a simple Java class called Metric which has two fields: MetricType and value: 我有一个名为Metric的简单Java类,它有两个字段:MetricType和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. 当从mongo读取指标时,我想要一个MetricType的自定义转换器,它将未映射到枚举的任何内容转换为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 我使用的是spring-boot-starter-data-mongodb 1.5.9版
what I tried doing is creating a Converter from string to MetricType 我尝试做的是创建一个从字符串到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: 并在mongoConfig文件中添加:
@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? 我确实看到转换器已在mongoTemplate中注册但转换器未被调用...我在这里缺少什么?
thanks! 谢谢!
You could try to use MongoCustomConversions instead of org.springframework.data.convert. 您可以尝试使用MongoCustomConversions而不是org.springframework.data.convert。 CustomConversions .
CustomConversions 。 MongoCustomConversions is a subclass of CustomConversions
MongoCustomConversions是CustomConversions的子类
But the ideal would be not to require any conversions at all or that the converter could be configurable inside the enums. 但理想情况是根本不需要任何转换,或者转换器可以在枚举内配置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.