Spring不使用mongo自定义转换器 [英] Spring not using mongo custom converters

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

问题描述

我一直在尝试注册自己的自定义转换器以更改默认ID值。
但它实际上从未打过电话。
这是我的自定义转换器

I have been trying to register my own write custom converters to change the default ID value. But it never actually calls. Here is my Custom Converter

public class EventKeyConverter implements Converter<Event,DBObject> {

    @Override
    public DBObject convert(Event object) {
        DBObject dbObject = DBObjectTransformer.toDBObject(object);
        dbObject.put("_id", KeyGenerator.getRandomKey());
        return dbObject;
    }

}

这里是我做的地方注册客户转换器

here is the place that I did register customer converter

@Override
@Bean
public CustomConversions customConversions() {
    List<Converter<?, ?>> converters = new ArrayList<Converter<?, ?>>();
    converters.add(new EventKeyConverter());
    return new CustomConversions(converters);
}

@Override
@Bean
public MappingMongoConverter mappingMongoConverter() throws Exception {
    MappingMongoConverter converter = new MappingMongoConverter(
            eventsMongoDbFactory(), mongoMappingContext());
    converter.setCustomConversions(customConversions());
    return converter;
}

@Bean
public MongoTemplate eventsMongoTemplate() throws Exception {
    final MongoTemplate template = new MongoTemplate(
            eventsMongoDbFactory(), mappingMongoConverter());
    template.setWriteResultChecking(WriteResultChecking.EXCEPTION);

    return template;
}

当我保存一些对象时,这个转换器永远不会被调用。

When I'm saving some objects this converter never gets called.


编辑1
我需要将默认对象Id更改为所有存储库中的某个自定义ID(UUID +随机密钥)。这就是我尝试使用mongo转换器的原因。

Edit 1 : I need to change the default object Id into some custom Id (UUID + random key) in all repositories. That why I tried to use mongo converter.

编辑2:
刚发现问题。在包含customConversion()的类中将@Configuration更改为@Component,它可以正常工作。但还是想知道这里发生了什么?

Edit 2 : Just found the issue. Change @Configuration to @Component in class that contains customConversion() and it works fine. But still wondering what is happened here ?

推荐答案

@Configuration 定义一个Spring上下文片段,其中包含if的方法用 @Bean 注释,返回新bean并将它们放在上下文中。

@Configuration defines a Spring context fragment that contains methods that if annotated with @Bean return new beans and put them in the context.

@Component 是一种说这个Pojo是一个Spring bean的方式。然后,您需要一个 @ComponentScan 注释或XML等价物来扫描 @Component 带注释的bean的包。

@Component is a way of saying "this Pojo is a Spring bean". You then need a @ComponentScan annotation or XML equivalent to scan packages for @Component annotated beans.

所以在你的情况下,你创建转换器很好,但是在你添加 @Component 之前它没有被注册为Spring bean ,所以它最初没有用。

So in your case, you created the converter fine, but it wasn't registered as a Spring bean until you added the @Component, so it didn't work initially.

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

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