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。
所以這與@ ComponentScan的basePackages沒有關係? – gyoder 2014-09-02 12:47:24
我添加了@EnableJpaRepositories(basePackages =「org.demo.jpa.repo」),但現在我得到了org.demo.jpa.repo.MyDomainObject的「Not a managed type」異常。我將不得不創建自己的EntityManagerFactory並指定要掃描的軟件包嗎? – gyoder 2014-09-02 12:59:57
不,您還需要'@ EntityScan'(根據上面鏈接的文檔)。 – 2014-09-02 14:48:07