mongodb - 如何使用 Micronaut 和 Kotlin + KMongo 为 MongoDB 配置对象映射?

标签 mongodb kotlin micronaut kmongo

我在使用 Kotlin 在 Micronaut 中为 MongoDB 配置对象映射时遇到了一些困难。我收到如下错误:

Decoding into a 'Asset' failed with the following exception:

Cannot find a public constructor for 'Asset'.

A custom Codec or PojoCodec may need to be explicitly configured and registered to handle this type. org.bson.codecs.configuration.CodecConfigurationException: An exception occurred when decoding using the AutomaticPojoCodec. Decoding into a 'Asset' failed with the following exception:

Cannot find a public constructor for 'Asset'.

A custom Codec or PojoCodec may need to be explicitly configured and registered to handle this type.

使用 KMongo,这很容易。然而,Micronaut 注入(inject)的 MongoClient 没有 KMongo 的编解码器注册表。

我可以让它按如下方式工作:

    val db: MongoDatabase by lazy {
        val codecRegistry = ClassMappingType.codecRegistry(MongoClientSettings.getDefaultCodecRegistry())
        client.getDatabase("db-name").withCodecRegistry(codecRegistry)
    }

此代码直接取自 KMongo。 (顺便说一句,使用 database.withKMongo() 导致了同样的错误)

虽然这可行,但我希望让 Micronaut 使用 KMongo 创建客户端,或者让它像上面那样使用其编解码器,使用配置 (application.yml)。

此处提到了一个codec-registry 设置:https://micronaut-projects.github.io/micronaut-mongodb/latest/guide/configurationreference.html ,但我不知道在该设置中输入什么才能使其正常工作。

感谢任何帮助!

最佳答案

您可以简单地将编解码器注册表定义为一个 bean。由于您无法控制正在注册的类,因此您可以创建一个工厂

@Factory
class KMongoFactory {

    @Singleton
    fun kCodecRegistry(): CodecRegistry {
        return ClassMappingType.codecRegistry(MongoClientSettings.getDefaultCodecRegistry());
    }

}

类似上面的东西应该可以做到

编辑:请注意 MongoClients.getDefaultCodecRegistry() 是默认添加的

关于mongodb - 如何使用 Micronaut 和 Kotlin + KMongo 为 MongoDB 配置对象映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54714058/

相关文章:

node.js - 使用nodejs通过_id删除mongodb中的查询

multithreading - 具有协程异步构造的自定义线程池

arrays - 在Kotlin中初始化交错阵列

websocket - Micronaut Websocket 连接每 5 分钟超时一次

node.js - 如何从 MongoJS 查询输出中选择值

c# - 如何设置MongoDB自动为每个子文档分配ID?

javascript - 列出 Meteor 用户 Collection View 中的数组对象值

java - Android Espresso 测试 : Illegal class access: 'androidx.test.core.app.ListFuture' attempting to access 'androidx.concurrent.futures.DirectExecutor'

java - 你是直接通过http传递hibernate/jpa实体对象还是有更好的选择?

java - 在 Micronaut,我如何获取对象数组作为配置属性