1

我想用 Spring 数据 mongodb 实现自定义 repo。应用程序.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.
4

1 回答 1

3

您必须让 Spring了解您的存储库。对于 Spring Boot 应用程序,这通常通过将此注释添加到您的应用程序来完成...

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

.... 从而告诉 Spring Boot 在哪里寻找 Mongo 存储库,然后让您的接口扩展org.springframework.data.mongodb.repository.MongoRepository

例如:

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

或者,您可以注释您CustomCustomerRepositoryImpl@Repository并确保它位于 Spring Boot 扫描的包中。

于 2017-10-21T12:25:24.223 回答