【问题标题】:2 beans with same name but different package, how to autowire?2个同名但不同包的bean,如何自动装配?
【发布时间】:2013-01-08 04:04:26
【问题描述】:

在我的 java 项目中,我有 2 个名称相同但包不同的实体,我也有这些实体对应的 dao。

现在因为有 2 个实体同名,所以出现重复扫描错误,所以我用它们的完全限定名称为这些实体添加了 name 属性。

例如:Entity(name="p.c.k.Entity) & Entity(name="p.a.b.Entity)

但现在我他们对应的 daos 无法自动装配,我收到以下错误:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type...

我是否还必须更改 Dao 中的任何内容以支持实体中的这种“名称”属性更改。

我正在使用 Hibernate、JPA 和 Spring。

【问题讨论】:

标签: java spring hibernate jpa


【解决方案1】:

我觉得你可以使用@Qualifier注解

@Autowired
@Qualifier("p.c.k.Entity")
private Entity entity;

来自here

【讨论】:

    【解决方案2】:

    默认情况下,自动装配是按类型完成的。所以你可以直接使用@Autowired注解,因为两个Entity都是不同的类,确保它们是spring bean(这里我的意思是它们是由Spring管理的)。

    @Autowired // nothing to specify, Spring automatically autowire the bean by checking type
    private p.c.k.Entity entity;
    @Autowired // nothing to specify, Spring automatically autowire the bean by checking type
    private p.a.b.Entity entity1;
    

    【讨论】:

      【解决方案3】:

      我也遇到了这个问题,除了重命名其中一个类之外,找不到任何解决方法。分在不同的包里应该就够了,但事实并非如此。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-26
        • 1970-01-01
        • 1970-01-01
        • 2012-05-19
        • 1970-01-01
        • 2014-12-14
        • 2017-04-26
        相关资源
        最近更新 更多