我有一个JpaRepository接口,当它与包含@ComponentScan的主类放在一个单独的包中时,Spring数据没有实现(或注入?)。
我的包结构(仅用于演示错误):
- org.demo.jpa.myapp Application.java - org.demo.jpa.repo MyDomainObject.java MyRepository.java
MyRepository.java
public interface MyRepository extends JpaRepository<MyDomainObject, Long> { }
应用程序
@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 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)
当MyRepository和MyDomainObject与Application类位于同一程序包中时, 不会引发 此错误。
这使用的是spring-boot-starter-parent 1.1.5.RELEASE和spring-boot-starter-data-jpa。
这可能是预期的行为(请参阅此处的文档)。包含封装@EnableAutoConfiguration实际上是两个默认的猜测@EnableJpaRepostories和@EntityScan。如果这些软件包与主autoconfig软件包脱节,则将需要这两个软件包。
@EnableAutoConfiguration
@EnableJpaRepostories
@EntityScan