16

I'm using Spring-Data for MongoDB:

Version information - org.mongodb.mongo-java-driver version 2.10.1, org.springframework.data.spring-data-mongodb version 1.2.1.RELEASE.

I have a case that's similar to the one defined in here, which is (sorry for the formatting...):

I just started developing some app in Java with spring-data-mongodb and came across some issue that I haven't been able to solve:

I have a couple of document beans like this:

@Document(collection="myBeanBar")
public class BarImpl implements Bar {
    String id;
    Foo foo;
    // More fields and methods ... 
}

@Document
public class FooImpl implements Foo {
    String id;
    String someField;
    // some more fields and methods ...
} 

And I have a repository class with a method that simply invokes a find similar to this:

public List<? extends Bar> findByFooField(final String fieldValue) {
    Query query = Query.query(Criteria.where("foo.someField").is(fieldValue));
    return getMongoOperations().find(query, BarImpl.class);
} 

Saving a Bar works just fine, it would save it in mongo along with the "_class" attribute for both Foo and Bar. However, finding by some attribute in Foo would throw an exception like this:

Exception in thread "main" java.lang.IllegalArgumentException: No
property someField found on test.Foo!
    at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentPropertyPath(AbstractMappingContext.java:225)
    at org.springframework.data.mongodb.core.convert.QueryMapper.getPath(QueryMapper.java:202)
    at org.springframework.data.mongodb.core.convert.QueryMapper.getTargetProperty(QueryMapper.java:190)
    at org.springframework.data.mongodb.core.convert.QueryMapper.getMappedObject(QueryMapper.java:86)
    at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1336)
    at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1322)
    at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:495)
    at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:486)

The solution that was given was to use the @TypeAlias annotation on the abstract class, which told the framework to use a specific implementation (in this case FooImpl).

In my case, I have interface members, instead of abstract members:

@Document(collection="myBeanBar")
public class BarImpl implements Bar {
    String id;
    IFoo foo;
    // More fields and methods ...
}

I'm very reluctant to put an annotation on the interface IFoo that will give a default implementation, instead I'd like to tell the framework what this field's default implementation in the context of the implementing BarImpl class, similar to @JsonTypeInfo:

@Document(collection="myBeanBar") 
public class BarImpl implements Bar {
    String id;    

    @JsonTypeInfo(use = Id.CLASS, defaultImpl = FooImpl.class)
    IFoo foo; 

    // More fields and methods ... 
}

I found this answer, which more or less says to avoid using interfaces. but I'd be happy to know if there's no better option.

Any ideas?

Thanks!

6
  • Which version of Spring Data MongoDB are you using? Jul 30, 2013 at 15:04
  • Right, I added the version information - org.mongodb.mongo-java-driver version 2.10.1, org.springframework.data.spring-data-mongodb version 1.2.1.RELEASE.
    – Ido Cohn
    Jul 30, 2013 at 15:12
  • 2
    Feels like you stumbled over jira.springsource.org/browse/DATACMNS-311. Do you have Spring Data Commons 1.5.1 on the classpath. This is the version the bug was fixed in. Jul 30, 2013 at 16:04
  • Hey @OliverGierke, yes - that's the version I have in my path. Thanks for the link, seems like I can't fix this while still using interfaces, so I had to use the implementing class instead. I hope they fix it sometime soon.
    – Ido Cohn
    Aug 1, 2013 at 10:59
  • I had the same problem and ended up using a wrapper around the class I wanted. For example, class Thing has a Foo and a Bar (but not both), then use Thing to persist. On the way back get a thing.isFoo(); and thing.getFoo() Apr 14, 2014 at 20:32

5 Answers 5

10

My problem is similar to the question, but the exception thrown is a bit different:

Could not instantiate bean class [class name]: Specified class is an interface

This happens when one of the fields of my DB class is declared as an interface. Saving this field is fine but exception thrown when reading it from MongoDB. Finally I found the solution that makes use of org.springframework.core.convert.converter.Converter.

TWO steps to do, 1. construct a class that implements Converter; 2. register the converter in the servlet context. And YES, you don't have to modify any existing code, such as adding annotation.

Below is my model class, where the field Data is an interface:

@Document(collection="record")
public class Record {
    @Id
    private String id;

    // Data is an interface
    private Data data;

    // And some other fields and setter/getter methods of them
}

The converter:

@ReadingConverter
public class DataReadConverter implements Converter<DBObject, Data> {
    @Override
    public Data convert(DBObject source) {
        // Your implementation to parse the DBObject,
        // this object can be BasicDBObject or BasicDBList,
        // and return an object instance that implements Data.

        return null;
    }
}

The last thing to do is to register the converter, my configuration is in xml:

<mongo:mongo id="mongo" />

<mongo:db-factory mongo-ref="mongo" dbname="example" />

<mongo:mapping-converter>
    <mongo:custom-converters>
        <mongo:converter>
            <beans:bean class="com.example.DataReadConverter" />
        </mongo:converter>
    </mongo:custom-converters>
</mongo:mapping-converter>

<beans:bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <beans:constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
    <beans:constructor-arg name="mongoConverter" ref="mappingConverter" />
</beans:bean>

Deploy the application and try again. It should properly parse the DBObject from MongoDB on the interface field.

The version of my Spring MongoDB application is : spring-*-4.1.0 and spring-data-mongodb-1.6.0.

1

I had the same error message as @victor-wong

Could not instantiate bean class [class name]: Specified class is an interface

The following code solves the problem with Spring Boot 2.3.2 and spring-data-mongodb 3.0.2

The converter:

import org.bson.Document;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.convert.ReadingConverter;

@ReadingConverter
public class DataReadConverter implements Converter<Document, Data> {

    @Override
    public Data convert(Document source) {

        return new DataImpl(source.get("key"));
    }
}

The last thing to do is to register the converter

    @Bean
    public MongoCustomConversions customConversions() {
        return new MongoCustomConversions(
                List.of(
                        new DataReadConverter()
                )
        );
    }

Additional information may be found here: https://jira.spring.io/browse/DATAMONGO-2391

1

While the solution with converter provided in other answers will work, it will require you to write a converter for every polymorphic filed. This is tedious and error-prone as it requires you to keep those converters in mind each time you add a new polymorphic field or change existing models.

Instead of writing a converter you can just configure type mappings. Moreover, you can make it work automagically. Here's how:

  1. First we’re going to need the reflections library. Pick the latest version for the build tool of your choice here.

    For example with Gradle:

    implementation("org.reflections:reflections:0.10.2")
    
  2. Now we’re going to need a small extension to DefaultMongoTypeMapper to make it easy to configure and instantiate. Here’s how it would look in Kotlin:

    class ReflectiveMongoTypeMapper(
        private val reflections: Reflections = Reflections("com.example")
    ) : DefaultMongoTypeMapper(
        DEFAULT_TYPE_KEY,
        listOf(
            ConfigurableTypeInformationMapper(
                reflections.getTypesAnnotatedWith(TypeAlias::class.java).associateWith { clazz ->
                    getAnnotation(clazz, TypeAlias::class.java)!!.value
                }
            ),
            SimpleTypeInformationMapper(),
        )
    )
    

    where com.example is either your base package or the package with MongoDB models.

    This way we will find all classes annotated with @TypeAlias and register alias to type mappings.

  3. Next we'll need to adjust the app's mongo configuration a bit. The configuration has to extend AbstractMongoClientConfiguration and we need to override method mappingMongoConverter to make use of the mapper we created before. It should look like this:

    override fun mappingMongoConverter(
        databaseFactory: MongoDatabaseFactory,
        customConversions: MongoCustomConversions,
        mappingContext: MongoMappingContext,
    ) = super.mappingMongoConverter(databaseFactory, customConversions, mappingContext).apply {
        setTypeMapper(ReflectiveMongoTypeMapper())
    }
    
  4. Done!

Now all alias to type mappings will be registered automatically on context startup and all your polymorphic fields will work just fine. No need to write and maintain converters.

You can check the full code example on GitHub.

Also, here's a blog post where you can read about the root cause of this issue as well as check other ways to solve it (in case you don't want to rely on reflection): https://blog.monosoul.dev/2022/09/16/spring-data-mongodb-polymorphic-fields/

1
  • Thank you @andrei-nevedomskii! Your solution with ConfigurableTypeInformationMapper on top of reflections library really works for polymorphic fields. Out of the box Spring Data supports only TypeAlias for Documents but fields I had to keep with default class names because the DefaultMongoTypeMapper don't see the TypeAlias on classes we use for Fields. Finally I can get rid of full class names from our database.
    – vbg
    Mar 21 at 22:22
0

I had the same problem with polimorphic deserialization. Basically I was importing data from two sources (REST API and ETL). The REST API imports with Spring Data were ok because they had the "_class" field so deserialization was not an issue. But the ETL imported data did not have the "_class" fields so when deserializing into the interface it did not know which concrete class to use.

I did try to extends the DefaultMongoTypeMapper, but that did not work because I was trying to map a field that did not exist in the Mongo Document.

So, the solution that worked for me was to intercept the deserialization between the moment the Document reaches the app but before deserialization starts. At this moment I can simply verify if the "_class" field exists, and if not I identify the type of the document and add the "_class" field with the corresponding concrete class.

This is done by overriding the onAfterLoad() of the AbstractMongoEventListener.

@Slf4j
@Component
public class WrapperRepositoryListener extends 
AbstractMongoEventListener<Data> {
    @Override
    public void onAfterLoad(AfterLoadEvent<Data> event) {
         Document field = Document)event.getDocument().get(ROOT_FIELD);
         final String type = String.valueOf(field.get("type")).toLowerCase();

         switch (type) {
            case TYPE -> field.put("_class", CLASSNAME);
            default -> log.debug("Type is not supported: " + type);
         }
}

}

I hope this helps anyone who lands on this page.

-2

This is really bad idea to define interfaces as field in data object.

Interface means possibility of some object to do something, but don't provide any information about fields. Do you really need to use interfaces? Can you avoid this? Even using abstract class definition will be better idea.

P.S. off course, my answer can't be marked as correct answer in any case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.