JpaRepository未在componentscan的独立包中实现/注入

gyo*_*der 6 spring-data-jpa spring-boot

我有一个JpaRepository接口,当它与包含@ComponentScan的主类在一个单独的包中时,它没有被Spring数据实现(或注入?).

我的包结构(仅为了演示错误):

- org.demo.jpa.myapp
    Application.java
- org.demo.jpa.repo
    MyDomainObject.java
    MyRepository.java
Run Code Online (Sandbox Code Playgroud)

MyRepository.java

public interface MyRepository extends JpaRepository<MyDomainObject, Long> { }
Run Code Online (Sandbox Code Playgroud)

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!");
        }
    }                
}
Run Code Online (Sandbox Code Playgroud)

例外

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)
Run Code Online (Sandbox Code Playgroud)

当MyRepository和MyDomainObject与Application类位于同一个包中时,不会抛出此错误.

这是使用spring-boot-starter-parent 1.1.5.RELEASE和spring-boot-starter-data-jpa.

Dav*_*yer 9

这可能是预期的行为(参见此处的文档).包含封装@EnableAutoConfiguration实际上是两个默认的猜测@EnableJpaRepostories@EntityScan.如果这些软件包与主autoconfig软件包分离,则需要两者.

  • 我通常建议将`Application`类保留在应用程序的根目录中.通过这种方式,您可以避免大量显式配置,因为所有内容都是透明地拾取的. (5认同)