jalv1039
jalv1039

Reputation: 1682

Abstract class inheritance with @Component (NoUniqueBeanDefinitionException)

I am trying to create a structure with inheritance for my @Component classes in order to reuse some common code. But I am getting a runtime error:

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.example.myproject.MainComponent] is defined: expected single matching bean but found 2: A,B

So, I have created 3 classes as follows:

public abstract class MainComponent {
    ...
    void myMethodToOverride();
    void myCommonMethod() {
        // Some common code for A and B
    }
    ...
}

@Component
public class A extends MainComponent {
    ...
    @Override
    void myMethodToOverride() {
        // Some specific code of A class
    }
    ...
}


@Component
public class B extends MainComponent {
    ...
    @Override
    void myMethodToOverride() {
        // Some specific code of B class
    }
    ...
}

Is it possible to this kind of inheritance with @Component of Spring (I am using 4.2.4 version)?

Upvotes: 0

Views: 1391

Answers (1)

Simon Martinelli
Simon Martinelli

Reputation: 36203

As Arnaud already mentioned you have an @Autowire with MainComponent.

To work around this you can use @Qualifier like descirbed here:

https://spring.io/blog/2014/11/04/a-quality-qualifier

Upvotes: 1

Related Questions