Spring中抽象类中能不能进行 @autoware?

之前做项目中,有时候会突发奇想,这个就是在菜鸟阶段想到的,所以对java思想理解的比较低,勿喷。

当时还真发现一些有意思的东西,我们可以思考下,
(1)stackoverflow中的一个答案,说的是,抽象类不能被实例化,需要进行继承实现;当你去继承之后,实现了抽象方法时,此时会创建一个匿名类,不是父类的实例化;有多个子类实现时,进行autoware注入,spring不知道which bean去注入;
(2)Abstract classes can’t be instantiated, you need to use a concrete implementation. Same as in regular java, if you try to instantiate an abstract class, it tells you to implement the abstract methods within. When you do, an anonymous class is created. It’s not an instatiation of the abstract class, but a new subclass of that abstract class.

Spring will look for classes which extend your base class, being Report1 and Report2, Spring sees it has multiple classes which match the requirements and doesn’t know which one to choose. thus you get the error that there are multiple matching beans.

You can fix this by making an “adapter” basicly create a concrete class which extends your base-class, implements the abstract methods, but doesn’t do anything them. Then you can autowire that implementation and test against it. However your abstract class should allready be tested due to the fact you are testing report 1 and 2. If errors still occur with your base class, it means logic you don’t use is causing bugs, which is a bad practice anyway. also with a test coveage tool you could spot unused code that way.
(3)在抽象类中需要注入(@autowire),在继承了该抽象类的子类中同样需要再次注入。比如在项目中用户购买物品的模板抽象类中需要使用userservice,则在改抽象类中和道具服务类(实现了道具接口并继承了模板抽象类)均需要对userservice进行注入。