簡體   English   中英

Spring&沒有獨特的bean類型

[英]Spring & No unique bean of type

我有以下Beans for Spring單元測試:

abstract class A {
    // some injections using @Value
}

class B extends A {
    // some injections using @Autowired, @Qualifier, @PersistenceUnit and @Value
}

class C extends A {
    // some injections using @Autowired, @Qualifier, @PersistenceUnit and @Value
}

class Foo{

    @Autowired
    private A a;

    ...
}

class BarTest{

    @Autowired
    private B b;

    @Autowired
    private C c;

    @Autowired // Expected: fooB.a = b
    private Foo fooB;

    @Autowired // Expected: fooC.a = c
    private Foo fooC;

    ...
}

在BarTest類中:是否可以控制注入Foo的2個實例的內容?

或者我有設計問題,我應該設置不同的東西?

您可以控制通過限定符注入的內容。

但在這種情況下,你的Foo類不會是單身人士。 因此,您很可能必須通過XML實例化(至少 - 根據您的需要)兩個Foo對象。

像這樣:

<beans ... >
    <bean id="b" class="your.pack.B" >
    <bean id="c" class="your.pack.C" >
    <bean id="fooB" class="your.pack.Foo" >
        <property name="a" ref="b" />
    </bean>
    <bean id="fooC" class="your.pack.Foo" >
        <property name="a" ref="c" />
    </bean>

...
</beans>

-

@Autowired // Expected: fooB.a = b
@Qualifier("fooB")
private Foo fooB;

@Autowired // Expected: fooB.a = c
@Qualifier("fooC")
private Foo fooC;

(並擺脫Foo類中的@Autowired注釋)

作為@Qualifier的替代,您可以使用javax.annotation.Resource注釋

@Resource(name = "fooB")
private Foo fooB;

@Resource(name = "fooC")
private Foo fooC;

您需要指定@Qualifier

@Qualifier("C")
@Autowired
private C c;

@Qualifier("B")
@Autowired
private B b;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM