Spring Bean implementation of multiple interfaces

I have a bean that implements two interfaces. The barebones code looks like this:

interface InterfaceA {
  ...
}

interface InterfaceB {
  ...
}

public class ClassC implements InterfaceA, InterfaceB {
  ...
}

      

In my AppConfig, I specify the following:

@Bean(name = "InterfaceA")
public InterfaceA interfaceA() {
    return new ClassC();
}

@Bean(name = "InterfaceB")
public InterfaceB interfaceB() {
    return new ClassC();
}

      

And I use it like this:

public class MyClass {

    @Inject
    private final InterfaceA a;

    public MyClass(@Named("InterfaceA") InterfaceA a) {
        this.a = a;
    }
     ...
}

      

However, Spring complains that:

No qualifying bean of type [com.example.InterfaceA] is defined: expected single bean match, but found 2: InterfaceA, InterfaceB

A similar question has been asked and answered for EJB here , but I couldn't find anything for Spring beans. Does anyone know the reason?

Workaround is to introduce a new interface that extends both InterfaceA

, and InterfaceB

then let them ClassC

implement it. However, I cannot change my design due to the limitations of the structure.

+3


source to share


1 answer


Spring is right ... when you write

@Bean(name = "InterfaceA")
public InterfaceA interfaceA() {
    return new ClassC();
}

@Bean(name = "InterfaceB")
public InterfaceB interfaceB() {
    return new ClassC();
}

      

Spring creates objects ClassC

, one named InterfaceA

, one InterfaceB

that implements InterfaceA and InterfaceB.

Then when you write:

@Inject
private final InterfaceA a;

      



ask Spring to find a bean implementation InterfaceA

, but as said above there are 2, so the error is.

You can create just one object of type ClassC

or use annotations @Qualifier

or @Named

:

@Inject
@Named("InterfaceA")
private final InterfaceA a;

      

So you are explicitly asking Spring to find a bean with a name InterfaceA

, and hopefully it is now unique.

0


source







All Articles