首页 > 解决方案 > 存储库接口的 Spring Data MongoDb bean xml 配置

问题描述

xml我有一个使用配置的现有 spring 应用程序。现在,我将使用spring-data-mongodb它连接到 Mongo 数据库。我repository/dao的都是这样的接口:

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

在我的服务类CustomerService中,它自动装配CustomerDao接口。

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

但由于CustomerDao是一个接口,我总​​是收到错误:

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

基于spring-data-mongodb存储库的教程主要是扩展至MongoRepository.

我的问题是,如果我不在配置中创建 bean 条目,则在类CustomerDao内部自动装配时会出错。以下是我得到的错误:CustomerServicexml

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)}

标签: javaspringspring-data-mongodb

解决方案


您可以只指定存储库包位置(和自定义实现,如果需要)。

然后,您可以创建一个扩展 mongo-spring-data 存储库之一的接口(我更喜欢 PagingAndSortignRepository)

之后,您将能够自动装配您的存储库。

不要忘记检查组件扫描包- 您的存储库和服务应该在那里。

最后一件事 - 检查您的服务上的Spring 注释


推荐阅读