在抽象基类中使用@autowired [英] use @autowired in abstract base class
问题描述
据我所知,不推荐字段注入
。应该使用构造函数
。
As I know, field injection
is not recommended. Should use constructor
instead.
我在这里尝试做的是使用 @在基类的构造函数中自动装入
,并使其可供所有子类访问。在某些子类中,我还需要一些特定的bean来自它们的构造函数 @Autowired
。演示代码如下:
What I'm trying to do here is using @Autowired
in the constructor of the base class, and make it accessible for all the subclasses. In some subclasses, I also need some specific beans to be @Autowired
from their constructors. Demo code is as following:
基类:
public abstract class Base {
protected final MyDemoService myDemoService;
@Autowired
public Base(MyDemoService myDemoService) {
this.myDemoService = myDemoService;
}
}
继承(子)类:
public class Sub extends Base {
private final MySubService mySubService;
@Autowired
public Sub(MySubService mySubService) {
this.mySubService = mySubService;
}
}
这将给我一个'无默认构造函数'错误。
类似于以下问题:类似的问题和答案,但它在这里不起作用。
This will give me a 'no default constructor' error.
It's similar to the question: similar question and answer, but it doesn't work here.
我已经潜入了一段时间,我发现这篇文章关于依赖注入
:进一步阅读
I have dived into this for a while, I found this article about dependency injection
: further read
我认为 Setter Injection
是我问题的正确方法吗?
I'm thinking is the Setter Injection
a right way for my question?
Setter注入:
public abstract class Base {
protected MyDemoService myDemoService;
@Autowired
public void setMyDemoService(MyDemoService myDemoService) {
this.myDemoService = myDemoService;
}
}
我是Java Spring Boot的新手,并且想要从你们那里获得一些专业知识。任何讨论都将受到高度赞赏!
I'm new to Java Spring Boot, and want to get some expertise advise from you guys. Any discussion will be highly appreciated!
推荐答案
您提供的代码将无法编译。只要在您的基类中没有默认构造函数,就应该在子代中调用 super(MyDemoService)
。
The code that you provide won't compile. As long as in your base class you don't have the default constructor, you should call super(MyDemoService)
in child.
继承(子)类:
public class Sub extends Base {
private final MySubService mySubService;
@Autowired
public Sub(MySubService mySubService, MyDemoService myDemoService){
super(myDemoService);
this.mySubService = mySubService;
}
}
或者,如果 MySubService
是 MyDemoService的实现
@Autowired
public Sub(MySubService mySubService){
super(mySubService);
}
只要您的字段 MyDemoService myDemoService
在抽象类中是 protected
你可以在子类中使用它。
As long as your field MyDemoService myDemoService
in abstract class is protected
you can use it in subclasses.
如果你有多个实现 MyDemoService
,而不是必须使用<$ href =https:// stackoverflow中所述的 @Qualifier
。 com / questions / 26453618 / autowire-distinct-beans-in-abstract-class / 26454131#26454131>你提到的答案。
If you have multiple implementation of MyDemoService
, than you have to use @Qualifier
as described in the answer that you have mentioned.
public Sub(@Qualifier("MySubService") MyDemoService mySubService){
super(mySubService);
}
这篇关于在抽象基类中使用@autowired的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!