java 抽象类 注入_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进行注入。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值