自定义 MongoDB spring 数据存储库

Custom MongoDB spring data repository

我想用 Spring 数据 mongodb 实现自定义存储库。 Application.java:

@SpringBootApplication
public class Application implements CommandLineRunner{

    @Autowired
    private CustomerRepositoryCustom repo;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println(this.repo.customMethod());
    }
}

我的自定义存储库CustomerRepositoryCustom.java

public interface CustomerRepositoryCustom {
    List<Customer> customMethod();
}

自定义实现 CustomCustomerRepositoryImpl.java

  public class CustomCustomerRepositoryImpl implements CustomerRepositoryCustom {
        @Autowired
        private MongoTemplate mongoTemplate;

        @Override
        public List<Customer> customMethod() {
            return this.mongoTemplate.findAll(Customer.class);
        }

    }

代码结构

-Application.java
  dal
    model...
    repository
     -CustomCustomerRepositoryImpl.java
     -CustomerRepositoryCustom.java

当我尝试构建它时,出现错误:

    **Description**:
Field repo in socketApp.Application required a bean of type 'socketApp.dal.repository.CustomerRepositoryCustom' that could not be found.


**Action**:
Consider defining a bean of type 'socketApp.dal.repository.CustomerRepositoryCustom' in your configuration.

您必须Spring知道您的存储库。对于 Spring 引导应用程序,这通常是通过将此注释添加到您的应用程序来完成的...

@EnableMongoRepositories("com.package.path.to.repository")

... 从而告诉 Spring 引导到哪里寻找 Mongo 存储库,然后让您的界面扩展 org.springframework.data.mongodb.repository.MongoRepository

例如:

public interface CustomerRepositoryCustom extends MongoRepository {
    List<Customer> customMethod();
}

或者,您可以使用 @Repository 注释您的 CustomCustomerRepositoryImpl 并确保它位于由 Spring Boot.

扫描的包中