使用 Spring Boot 在 MongoTemplate 中注册 CustomConverter [英] Register a CustomConverter in a MongoTemplate with Spring Boot

查看:35
本文介绍了使用 Spring Boot 在 MongoTemplate 中注册 CustomConverter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Spring Boot 在我的 MongoTemplate 中注册自定义转换器?如果可能,我只想使用注释来做到这一点.

How can I register a custom converter in my MongoTemplate with Spring Boot? I would like to do this only using annotations if possible.

推荐答案

您需要为转换器配置创建一个配置类.

You need to create a configuration class for converter config.

@Configuration
@EnableAutoConfiguration(exclude = { EmbeddedMongoAutoConfiguration.class })
@Profile("!testing")
public class MongoConfig extends AbstractMongoConfiguration {
    @Value("${spring.data.mongodb.host}")  //if it is stored in application.yml, else hard code it here
    private String host;

    @Value("${spring.data.mongodb.port}")
    private Integer port;

    @Override
    protected String getDatabaseName() {
        return "test";
    }

    @Bean
    public Mongo mongo() throws Exception {
        return new MongoClient(host, port);
    }

    @Override
    public String getMappingBasePackage() {
        return "com.base.package";
    }

    @Override
    public CustomConversions customConversions() {
        List<Converter<?, ?>> converters = new ArrayList<>();
        converters.add(new LongToDateTimeConverter());
        return new CustomConversions(converters);
    }
}
@ReadingConverter
static class LongToDateTimeConverter implements Converter<Long, Date> {
    @Override
    public Date convert(Long source) {
        if (source == null) {
            return null;
        }
        return new Date(source);
    }
}

这篇关于使用 Spring Boot 在 MongoTemplate 中注册 CustomConverter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆