【问题标题】:Java, Springboot, MongoDB extend SimpleMongoRepository (2020)Java、Springboot、MongoDB 扩展 SimpleMongoRepository (2020)
【发布时间】:2020-05-10 14:02:10
【问题描述】:

我在 Stackoverflow 中发现了很多与此相关的问题。 但它们都是几年前的事了。希望找到更新的解决方案。

我在自己的类中扩展 SimpleMongoRepository 以添加一些自定义方法

这是我的代码。 MongoHelper.java

package com.customlibrary.mongodblibrary.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate; 
import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
import org.springframework.data.mongodb.repository.support.SimpleMongoRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import java.io.Serializable;

@Component
public class MongoHelper<T, ID extends Serializable> extends SimpleMongoRepository<T, ID> implements 
CustomerRepository<T , ID> {


/**
 * Creates a new {@link SimpleMongoRepository} for the given {@link MongoEntityInformation} and 
                 {@link MongoTemplate}.
 *
 * @param metadata        must not be {@literal null}.
 * @param mongoOperations must not be {@literal null}.
 */
public MongoHelper(MongoEntityInformation<T, ID> metadata, MongoOperations mongoOperations) {
    super(metadata, mongoOperations);
}

public void customMeth(){
    System.out.println("test");
}
}

这是我的代码。 CustomerRepository.java

@Repository
public interface CustomerRepository<Customer, String> extends MongoRepository<Customer, String> {

}

我已经把它放在我的主目录中了

@EnableMongoRepositories(repositoryBaseClass = MongoHelper.class)

但出现错误

Parameter 0 of constructor in com.customlibrary.mongodblibrary.service.MongoHelper required a bean of type 'org.springframework.data.mongodb.repository.query.MongoEntityInformation' that could not be found.

希望有人能给我一个解决方案

【问题讨论】:

    标签: java mongodb spring-boot


    【解决方案1】:

    使用 @NoRepositoryBean 而不是 @Component 用于 MongoHelper,因为 MongoHelper 应该是要扩展的基类,而不是 Spring 管理的 bean

    【讨论】:

    • 非常感谢。它让我受益匪浅。
    • 这是扩展 SimpleMongoRepository 的正确方法。感谢您的问题和答案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    • 2011-02-17
    • 2016-09-05
    • 2019-11-11
    • 2016-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多