JpaRepository not implemented/injected when in sep

2019-02-14 06:19发布

I have a JpaRepository interface that is not being implemented (or injected?) by Spring data when it's in a separate package from the main class containing the @ComponentScan.

My package structure (only for the sake of demonstrating the error):

- org.demo.jpa.myapp
    Application.java
- org.demo.jpa.repo
    MyDomainObject.java
    MyRepository.java

MyRepository.java

public interface MyRepository extends JpaRepository<MyDomainObject, Long> { }

Application.java

@Configuration
@ComponentScan(basePackages="org.demo.jpa")
@EnableAutoConfiguration
public class Application {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(Application.class, args);        
        if (context.getBean(MyRepository.class) == null){
            throw new NullPointerException("repo was not initialized!");
        }
    }                
}

The exception

Exception in thread "main" 2014-09-01 11:20:26.336  INFO 6156 --- [           main] org.demo.jpa.myapp.Application           : Started Application in 2.824 seconds (JVM running for
 3.362)
2014-09-01 11:20:26.339  INFO 6156 --- [       Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContex
t@5d50b632: startup date [Mon Sep 01 11:20:23 EDT 2014]; root of context hierarchy
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.demo.jpa.repo.MyRepository] is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:319)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:985)
    at org.demo.jpa.myapp.Application.main(Application.java:17)

This error is not thrown when MyRepository and MyDomainObject are in the same package as the Application class.

This is using spring-boot-starter-parent 1.1.5.RELEASE and spring-boot-starter-data-jpa.

1条回答
相关推荐>>
2楼-- · 2019-02-14 06:58

That's probably the expected behaviour (see docs here). The package containing the @EnableAutoConfiguration is actually the default guess for both @EnableJpaRepostories and @EntityScan. You will need both if those packages are disjunct from the main autoconfig package.

查看更多
登录 后发表回答