Search code examples
spring-bootspring-data-jpamaven-module

Accessing a Spring Boot Repository of an interface in a module from outside


Yes, Spring Data JPA is a nice feature, that delegates the creation/implementation of a database query to Springboot. I was able to use this simply by creation of a configuration class, that was annotated with @Configuration and @EnableJpaRepositories.

Now want to put all that DB related code in a maven-module and want to access this function from outside. In order to archive this i added a @Import(MyConfiguration.class) to my @SpringBootApplication class.

Unfortunately i am not able to access my repo, because i receive the following exception:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'de.demo.dbdomain.repo.MyRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1812) ~[spring-beans-6.0.5.jar:6.0.5]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1371) ~[spring-beans-6.0.5.jar:6.0.5]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1325) ~[spring-beans-6.0.5.jar:6.0.5]
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:709) ~[spring-beans-6.0.5.jar:6.0.5]
        ... 106 common frames omitted

I guess i need to initialize the code inside my module, but i don not know how.

I hope to get the initialisation of springJPA done with my @Import.


Solution

  • You also need to declare the package where spring-boot needs to scan for candidate repositories.

    So together with @SpringBootApplication you also need the:

    @EnableJpaRepositories(basePackages = {"package1", "package2"}) so that spring boot can look in the specific path of that module and register required repositories.

    In case you also have entities in this other module with @Entity you will also need the @EntityScan(basePackages = {"yourpackage3", "yourpackage4}).

    By default if those packages are not provided spring boot will look for spring annotations and repositories only in the package where the annotation @SpringBootApplication exists or deeper nested packages from the package where the annotation @SpringBootApplication exists.