Prashant Pandey
Prashant Pandey

Reputation: 4682

Spring Autowiring in Inherited Classes

Suppose I have a class A:

public class A {
    @Autowire embeddedKafka;
}

Suppose the following class extends A:

@SpringBootTest
public class B extends A {

}

Now when the object for class B is created, class A's constructor will be called. I am wondering if the embeddedKafka instance will be autowired? In my test, this is what I am observing. My question is this: when there is no instance of A getting created, why does Spring autowire the embeddedKafka instance?

Edit:

Upvotes: 0

Views: 694

Answers (1)

JB Nizet
JB Nizet

Reputation: 692281

B extends A. So an instance of B is an instance of A. So when an instance of B is being created, an instance of A is being created (just like, when you make a baby girl, you also make a baby human, because a girl is a human). You told it yourself: class A's constructor will be called.

If a class constructor is being called, then an instance of that class is being constructed, by definition.

Upvotes: 1

Related Questions