gpt4 book ai didi

java - spring - 具有范围原型(prototype)的抽象类中的 Autowiring 接口(interface)不起作用

转载 作者:行者123 更新时间:2023-12-02 02:12:00 24 4
gpt4 key购买 nike

我有一个example spring project我有一个抽象类 Athlete,我想在其中 Autowiring 接口(interface) Trainer

AthleteRunnable 且其实现覆盖perform() 方法。

当我在 Sprinter 中调用 perform() (扩展 Athlete)时,我想要的 Trainer 实例 Autowiring 到Athlete 仍然为空

运动员:

@Component
@Scope("prototype")
public abstract class Athlete implements Runnable{

protected final String name;

@Autowired protected Trainer trainer;


public Athlete(String name)
{
this.name = name;
}

protected abstract void perform();

@Override
public void run() {
perform();
}
}

短跑运动员:

@Component
@Scope("prototype")
public class Sprinter extends Athlete {

public Sprinter(String name) {
super(name);
}

@Override
protected void perform()
{
this.trainer.giveAdviceTo(name); // TRAINER IS NULL !!!!!!
for(int i=0;i<3;i++)
{
System.out.println("Sprinting...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
}

Trainer的实现

@Component
public class TrainerImpl implements Trainer{

@Override
public void giveAdviceTo(String name)
{
System.out.println("Go " + name + "!!");
}
}

感谢您的帮助

最佳答案

在我看来,在你的主类中,你正在自己创建这些对象。

Athlete a1 = new Sprinter("adam");

Spring 只能将对象 Autowiring 到(托管)bean 中。此时,Spring 根本不知道您创建的 Sprinter 实例是否存在。

当您让 Spring 为您创建 bean 时,它还会注入(inject)所有 @Autowired 依赖项。

@Autowired
private BeanFactory beanFactory;


@Override
public void run(String... args) throws Exception {
Sprinter adam = beanFactory.getBean(Sprinter.class, "adam");
TennisPlayer roger = beanFactory.getBean(TennisPlayer.class, "roger");

executor.execute(adam);
executor.execute(roger);
}

关于java - spring - 具有范围原型(prototype)的抽象类中的 Autowiring 接口(interface)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49882221/

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