2014-09-01 57 views
5

我有一個JpaRepository接口,當它位於包含@ComponentScan的主類的單獨包中時,Spring數據未實現(或注入?)。JpaRepository在組件包的獨立包中未實現/注入

我的封裝結構(僅用於演示錯誤的緣故):

- 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!"); 
     } 
    }     
} 

異常

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 
[email protected]: 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) 

當MyRepository和MyDomainObject與Application類位於同一個包中時,不會拋出此錯誤

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

回答

9

這可能是預期的行爲(請參閱docs here)。包含@EnableAutoConfiguration的包實際上是@EnableJpaRepostories@EntityScan的默認猜測。如果這些軟件包與主自動配置軟件包不相關,則需要兩者。

+0

所以這與@ ComponentScan的basePackages沒有關係? – gyoder 2014-09-02 12:47:24

+0

我添加了@EnableJpaRepositories(basePackages =「org.demo.jpa.repo」),但現在我得到了org.demo.jpa.repo.MyDomainObject的「Not a managed type」異常。我將不得不創建自己的EntityManagerFactory並指定要掃描的軟件包嗎? – gyoder 2014-09-02 12:59:57

+1

不,您還需要'@ EntityScan'(根據上面鏈接的文檔)。 – 2014-09-02 14:48:07