Search code examples
javaspringmongodbspring-bootmongorepository

Custom MongoDB spring data repository


I want to implement custom repo with Spring data 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());
    }
}

My custom repository CustomerRepositoryCustom.java

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

Custom implementation CustomCustomerRepositoryImpl.java

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

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

    }

Code Structure

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

When I try to build it, i get an error:

    **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.

Solution

  • You have to make Spring aware of your repository. For a Spring Boot application this is typically done by adding this annotation to your application ...

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

    .... thereby telling Spring Boot where to look for Mongo repositories and then let your interface extend org.springframework.data.mongodb.repository.MongoRepository.

    For example:

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

    Alternatively, you could annotate your CustomCustomerRepositoryImpl with @Repository and ensure that it is in a package which is scanned by Spring Boot.