简体   繁体   中英

Spring Data MongoDb bean xml configuration for repository interface

I have an existing spring application using xml configuration. Now, I will be using spring-data-mongodb to connect it to a Mongo database. My repository/dao are all interfaces like:

public interface CustomerDao extends MongoRepository<Customer, String> {
   ...
}

and inside my service class CustomerService it autowires CustomerDao interface.

<bean id="customerDao" class="com.myapp.repository.CustomerDao" />
<bean id="customerService" class="com.myapp.service.CustomerService">
    <property name="customerDao" ref="customerDao"/>
</bean>

but since CustomerDao is an interface, I am always getting the error:

org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.myapp.repository.CustomerDao]: Specified class is an interface

Based on the tutorials for spring-data-mongodb repositories are mostly interfaces extending to MongoRepository .

My problem is that, I am getting error when autowiring CustomerDao inside CustomerService class if I will not create a bean entry in the xml configuration. Below is the error I am getting:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.myapp.repository.CustomerDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=customerDao)}

You can just specify repositories package location (and custom implementations, if needed).

Then you can just create an interface extending one of the mongo-spring-data repositories (I prefer PagingAndSortignRepository)

After that you'll be able to Autowire your repos.

Don't forget to check component scan package - your repos and services should be there.

And the last thing - check for Spring annotations on your services

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM