简体   繁体   中英

Why can't we autowire an abstract class inside a concrete class in Spring?

public abstract class A{

}

class B{

@Autowired
A a;

}

Why doesn't this seem to work, when I can insert an interface into Spring ? Shouldn't it locate a concrete class that extends that abstract class A, and then wire it into the class B, like it does for interfaces ?

Just forget about the auto wiring, Here you cannot create an object of abstract class by its nature, But if you have at least one of the concrete class which extends this abstract then the spring is capable of auto wiring, In this case spring internally create an instance of concrete class first and then it will auto wire. Since here the abstract class is parent of the concrete class and it is capable of holding its child class objects.

After a research I came to know that, When we want to create the instance of abstract class(if we are not having any implementation classes) then JVM suggests to create the implementation classes. In the same way if we are talking about Spring, It is used to create the instances at very first time.

That is the error spring is going to tell. So after creating the implementation classes we can Autowire the abstract class inside another class.

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