I've found a workaround for this issue, but I don't like it so I thought I would bring it to your attention.
I've got a class Id for which I need a custom codec. Technically it is a POJO, but I need it structured differently than normal in the BSON (it's actually a wrapper for a string that gets converted to an ObjectId for use as _id). The Id class ideally should reside in a certain package which contains my other domain objects, because it is directly referenced and incorporated into them.
So I registered the overall package with the PojoCodecProvider, then built a registry around that with CodecRegistries.fromCodecs(new IdCodec())
and .fromRegistries(pojoCodecProvider)
. But no matter what order I did that registration, my custom codec was not being called. Only when I moved the Id class out of the registered package, was its codec used.
Example setup:
CodecRegistry overallRegistry = fromRegistries(
MongoClient.getDefaultCodecRegistry(),
fromCodecs(
new IdCodec()),
fromProviders(
new EnumCodecProvider(),
createPojoCodecProvider()));
private PojoCodecProvider createPojoCodecProvider() {
return PojoCodecProvider.builder()
.register(Id.class.getPackage().getName())
.build();
}
I tried switching the parameter order to fromRegistries
, creating an IdCodecProvider and putting it in the fromProviders
parameters, then varying the order of those parameters, etc.
One solution would be to annotate classes that should be excluded from the PojoCodecProvider's consideration. Or, the PojoCodecProvider.Builder could have an ignore(Class<?>)
method.
Curious your thoughts on this!