首页 文章

Spring Data Couchbase示例无法解析Repository实例

提问于
浏览
0

使用Couchbase企业版5.0.0版本2873和Spring Data Couchbase 2.1.2,我得到了问题底部解释的错误 . 如果你只需要短篇小说,那就前进吧 .

如果您想要更多解释,请点击此处:

想象一下,CrudRepository方法对我来说很好 . 我的意思是,我不需要再添加任何方法 .

存储库的外观如何?我会像这样声明一个空的存储库吗?

@Repository
public interface PersonRepository extends CrudRepository<Person, String> {
// Empty
}

或者我会直接使用CrudRepositoy作为我的Base存储库 . 我不这么认为,因为你需要将Type和ID传递给CrudRepository .

但问题不在于此 . 问题出在这里:

考虑到没有实现该基本存储库,Spring如何知道如何实例化PersonRepository?看一下PersonService和PersonServiceImpl接口/实现 .

接口:

@Service
public interface PersonService {
    Person findOne (String id);
    List<Person> findAll();
    //...
}

执行:

public class PersonServiceImpl implements PersonService {

    // This is the variable for the repository
    @Autowired
    private PersonRepository personRepository;

    public Person findOne(String id){
        return personRepository(id);
    }

    public List<Person> findAll(){
        List<Hero> personList = new ArrayList<>();

        Iterator<Person> it = personRepository.iterator();

        while (it.hasNext()){
            personList.add(it.next());
        }

        return personList;
    }
//...
}

声明从CrudRepository扩展的空PersonRepository真的够了吗?不需要实现和说出任何关于CrudRepository的每个方法的内容 . 至少要告诉Spring一些构造函数......

这个疑问都是因为我在Spring尝试注入personRepository变量时遇到了这个错误:

Error creating bean with name 'personRepository': Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities).

显然,它要求有一些类至少定义实现的构造函数 . 如何告诉Spring避免错误中提到的那些类型歧义?

1 回答

  • 0

    至于存储库,如果您严格使用Couchbase,则需要扩展 CouchbaseRepository ,因为您的存储库将公开较低级别的couchbase对象/功能 .

    例如

    public interface PersonRepository extends CouchbaseRepository<Person, String> {
    }
    

    对于您的服务,您不需要定义 findOne()findAll() ,这些都是存储库的责任 .

    例如

    public interface PersonService {
        void doOperationOnPerson(String personId);
    }
    
    @Service
    public class PersonServiceImpl implements PersonService {
        @Autowired
        PersonRepository personRepo;
    
        @Override
        void doOperationOnPerson(String personId) {
        Person person = personRepo.findById(personId);
        //do operation
        }
    }
    

    请注意, @Service 注释继续执行 . (它实际上应该以任何方式工作,但我认为在实现上有注释更多proper

    如果您需要定义自定义查询,那么它应该在存储库本身内完成 .

    如果您有非默认构造函数,还可能需要在 Person 类上定义一个空构造函数 .

    我建议你阅读更多关于Spring Data的内容 .

相关问题