spring-projects / spring-data-mongodb

Provides support to increase developer productivity in Java when using MongoDB. Uses familiar Spring concepts such as a template classes for core API usage and lightweight repository style data access.
https://spring.io/projects/spring-data-mongodb/
Apache License 2.0
1.61k stars 1.08k forks source link

Unable to Determine Generic Converter type #4730

Closed apurvaojas closed 3 months ago

apurvaojas commented 3 months ago

Spring version 'org.springframework.boot:spring-boot-starter-data-mongodb:3.3.0' Spring boot failing start with below error due to @ReadingConverter

Unable to determine source type <S> and target type <T> for your Converter [com.organic.forms.application.configurations.BsonToMyObjConverter]; does the class parameterize those types?

@ReadingConverter
public class BsonToMyObjConverter<T> implements Converter<Document, T> {

    private final MyBSONCodec codec;

    public BsonToMyObjConverter(MyBSONCodec codec) {
        this.codec = codec;
    }

    @Override
    public T convert(@NonNull Document document) {
        BsonDocument bsonDocument = BsonDocument.parse(document.toJson());
        BsonReader reader = new BsonDocumentReader(bsonDocument);

        return ((T) codec.decode(reader, DecoderContext.builder().build()));
    }
}
       @Bean
    public MongoCustomConversions customConversions() {
        List<Converter<?, ?>> converters = new ArrayList<>();
        converters.add(new BsonToMyObjConverter<MyObj>(new MyBSONCodec()));
        return new MongoCustomConversions(converters);
    }
mp911de commented 3 months ago

Generic converters aren't supported in that way as T is being erased to Object. Custom Conversions must know the target types (these could be also super-types or super-interfaces) in advance. You might want to have a look at GenericConverter that exchanges convertible types.