【问题标题】:Autowiring of bean not working context:component scanbean 的自动装配不工作上下文:组件扫描
【发布时间】:2014-04-11 18:21:55
【问题描述】:

玩弄原型。我有一个自动装配 JPARepository 的测试类

@ContextConfiguration("classpath:appContext-test.xml")
@Transactional
public class PersonRepositoryTest extends AbstractTransactionalJUnit4SpringContextTests {
    private static Logger logger = LoggerFactory.getLogger(PersonRepositoryTest.class);

    @Autowired
    PersonRepository personRepository;

我的 appContext-test.xml 可以正常工作

<jpa:repositories base-package="com.mycompany.rd.misf.repository" /> 

但当我试图了解 spring 时,我认为这也可能有效。所以我注释掉了 jpa:repositories 标签并用这个补充了我的组件扫描:

<context:component-scan base-package="com.mycompany.rd.misf.model,com.mycompany.rd.misf.repository" />

我的存储库用@Repository 注释

@Repository
public interface PersonRepository extends JpaRepository<Person, Long> {
    public List<Person> findByFirstNameAndLastName(String firstName,
            String lastName);

    @Query("select p from Person p where p.firstName = :firstName or p.lastName = :lastName")
    public List<Person> findByFirstNameOrLastName(
            @Param("firstName") String firstName,
            @Param("lastName") String lastName);

    public Page<Person> findAll(Pageable pageable);
}

但我遇到了例外:

无法自动装配字段: com.mycompany.rd.misf.repository.PersonRepository com.mycompany.rd.misf.repository.PersonRepositoryTest.personRepository; 嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: 否 类型的限定 bean [com.mycompany.rd.misf.repository.PersonRepository] ​​找到 依赖项:预计至少有 1 个符合自动装配条件的 bean 这种依赖的候选人。依赖注解: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

为什么这不起作用?

我已经在我的 appContext-text.xml 文件中设置了。

任何帮助表示赞赏。

问候

【问题讨论】:

    标签: java spring


    【解决方案1】:

    Spring JPA 文档对jpa:repositories 进行了以下说明

    [...] Spring 被指示扫描 com.acme.repositories 及其所有用于扩展接口的子包 存储库或其子接口之一。对于找到的每个接口, 基础设施注册持久性技术特定的 FactoryBean 创建处理调用的适当代理 的查询方法。每个 bean 都注册在一个 bean 名称下 是从接口名派生出来的,所以是UserRepository的一个接口 将在 userRepository 下注册。 base-package 属性 允许通配符,以便您可以定义扫描的模式 包。

    所以

    <jpa:repositories base-package="com.mycompany.rd.misf.repository" /> 
    

    扫描该基础包及其所有子包以查找扩展 Repository 的类,JpaRepository 会这样做,因此您的 PersonRepository 接口会这样做,因此会创建一个 bean。

    这是 JPA 特有的行为。

    <context:component-scan base-package="com.mycompany.rd.misf.model,com.mycompany.rd.misf.repository" />
    

    您是在告诉 Spring 扫描指定的包及其子包以查找组件、使用 @Component 注释的类型及其特化。如果找到任何带注释的 classes,Spring 应该为它们创建一个 bean 定义。

    在您的情况下,它找到了@Component@Repository 的特化,但它是一个接口,因此它不注册 bean 定义。在这种情况下,它完全不了解 JPA。

    【讨论】:

    • 谢谢一百万,很好的解释,
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 2012-11-11
    • 2014-12-26
    • 2011-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多