Aditya
Aditya

Reputation: 1043

Spring Inheritance Autowired Annotations

For inheritance I see examples using XML Definition. I had a doubt using Autowire and Annotations.

I have

@Component
class A{

}

@Component
class B extends A{

}

class TestClass{
    @Autowire
    A aObj;
}

So I believe this will inject Object of Class A. Correct ? Also If I make my class A as abstract, it will inject Class B object. Correct ?

Also it would be good if someone can give me a link to example for this.

Upvotes: 2

Views: 2493

Answers (1)

Aditya
Aditya

Reputation: 1043

I tried the code and got the results as follows.

For above it throws NoUniqueBeanException.

  1. If I make Class A as abstract it injects Class B Bean and works fine.

  2. If I don't want to make class A as abstract I need to Use Qualifiers as follows

    @Component(value="aBean")
    class A{
    
    }
    
    @Component(value="bBean")
    class B extends A{
    
    }
    
    class TestClass{
        @Autowire
        @Qualifier(value="aBean")
        A aObj;
    }
    

    This injects Class A bean.

Upvotes: 4

Related Questions