简体   繁体   中英

Spring & No unique bean of type

I have the following Beans for Spring based unit test:

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;

    ...
}

In class BarTest: is it possible to control what gets injected into the 2 instances of Foo?

Or do I have a design issue and I should setup things differently?

You can control what gets injected via qualifiers .

But in this case your Foo class will not be a singleton. So, most likely you will have to instantiate (at least - depending on your needs) two Foo objects via XML.

Like this:

<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;

(And get rid of the @Autowired annotation in Foo class)

As an alternative to @Qualifier you can use javax.annotation.Resource annotation

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

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

You need to specify the @Qualifier

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM