自定义MongoDB spring数据存储库

时间:2017-10-21 12:03:31

标签: java spring mongodb spring-boot mongorepository

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

1 个答案:

答案 0 :(得分: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扫描的包中。