gpt4 book ai didi

java - 在抽象基类中使用 @autowired

转载 作者:IT老高 更新时间:2023-10-28 13:55:23 37 4
gpt4 key购买 nike

据我所知,不推荐字段注入(inject)。应该使用 constructor 代替。

我在这里尝试做的是在基类的构造函数中使用 @Autowired,并使其可供所有子类访问。在某些子类中,我还需要一些特定的 bean 从它们的构造函数中成为 @Autowired。演示代码如下:

基类:

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;
}
}

这会给我一个“没有默认构造函数”的错误。
类似于问题:similar question and answer ,但在这里不起作用。


我已经深入研究了一段时间,我发现了这篇关于依赖注入(inject)的文章:further read

我在想 Setter Injection 是否适合我的问题?

Setter 注入(inject):

public abstract class Base {

protected MyDemoService myDemoService;

@Autowired
public void setMyDemoService(MyDemoService myDemoService) {
this.myDemoService = myDemoService;
}
}

我是 Java Spring Boot 的新手,想从你们那里获得一些专业建议。任何讨论都将受到高度赞赏!

最佳答案

您提供的代码无法编译。只要在您的基类中没有默认构造函数,您就应该在子类中调用 super(MyDemoService)

继承(子)类:

public class Sub extends Base {

private final MySubService mySubService;

@Autowired
public Sub(MySubService mySubService, MyDemoService myDemoService){
super(myDemoService);
this.mySubService = mySubService;
}
}

或者,如果 MySubServiceMyDemoService

的实现
@Autowired
public Sub(MySubService mySubService){
super(mySubService);
}

只要你在抽象类中的MyDemoService myDemoService字段是protected的,你就可以在子类中使用它。

如果您有多个 MyDemoService 实现,则必须使用 answer that you have mentioned 中所述的 @Qualifier .

public Sub(@Qualifier("MySubService") MyDemoService mySubService){
super(mySubService);
}

关于java - 在抽象基类中使用 @autowired,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42713799/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com