Spring-boot:注册mongodb自定义转换器 [英] Spring-boot: register mongodb custom converter

查看:61
本文介绍了Spring-boot:注册mongodb自定义转换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将此依赖项用于我的 spring bott 服务:

I'm using this dependency into my spring bott service:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

我创建了一个自定义转换器:

I've created a custom converter:

import org.springframework.core.convert.converter.Converter;

@Component
public class ReferenceWriterConverter implements Converter<Reference, DBObject> {
    @Override
    public DBObject convert(Reference reference) {
        DBObject dbObject = new BasicDBObject();
        //...
        return dbObject;
    }
}

我想弄清楚如何注册"这个转换器.但是,在那里潜水我不太清楚我是否需​​要使用 CustomConvertions 类或 MappingMongoConverter.

I'm trying to figure out how to "register" this converter. However, diving over there I don't quite figure out whether I need to use a CustomConvertions class or MappingMongoConverter.

我需要如何将我的自定义转换器注册"到我的 Spring Boot 服务中?

How would I need to "register" my custom converter into my spring boot service?

有什么想法吗?

推荐答案

你需要覆盖 mongodb 的 customConversions,像这样:

You need to override the customConversions of mongodb, like so:

@Configuration
public class MongoConfig {

    @Bean
    public MongoCustomConversions customConversions(){
        List<Converter<?,?>> converters = new ArrayList<>();
        converters.add(ReferenceWriterConverter.INSTANCE);
        return new MongoCustomConversions(converters);
    }

    @WritingConverter
    enum ReferenceWriterConverter implements Converter<Reference, DBObject> {

        INSTANCE;

        @Override
        public String convert(Reference reference) {
            //do stuff
        }
    }
}

当然,您也可以像上面一样在单独的类中声明转换器,然后将其自动装配到配置中.

Of course, you can also declare the converter in your separate class like above and just autowire it into the configuration.

这篇关于Spring-boot:注册mongodb自定义转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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