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

栏目: 后端 · 前端 · 发布时间: 6年前

内容简介: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进行注入。


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Haskell Programming from first principles

Haskell Programming from first principles

Christopher Allen、Julie Moronuki / 2015 / USD 59.00

I am writing this book because I had a hard time learning Haskell. It doesn't have to be that way. I've spent the last couple years actively teaching Haskell online and in person. Along the way, I ......一起来看看 《Haskell Programming from first principles》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

在线进制转换器
在线进制转换器

各进制数互转换器

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具