JpaRepository 在与 componentscan 分开的包中未实现/注入 [英] JpaRepository not implemented/injected when in separate package from componentscan

查看:17
本文介绍了JpaRepository 在与 componentscan 分开的包中未实现/注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

MyRepository.java

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

应用程序.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
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 类在同一个包中时,不会抛出此错误.

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

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

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

推荐答案

这可能是预期的行为(参见 此处的文档).包含 @EnableAutoConfiguration 的包实际上是 @EnableJpaRepostories@EntityScan 的默认猜测.如果这些包与主自动配置包分离,您将需要两者.

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.

这篇关于JpaRepository 在与 componentscan 分开的包中未实现/注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆