gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 12:53:42 29 4
gpt4 key购买 nike

我在使用 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com