【发布时间】:2018-09-27 15:55:35
【问题描述】:
我有一个example spring project,我有一个抽象类Athlete,我想在其中自动装配一个接口Trainer。
Athlete 是Runnable,其实现会覆盖perform() 方法。
当我在Sprinter(扩展Athlete)中调用perform() 时,我想自动连接到Athlete 的Trainer 实例仍然为空
运动员:
@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 + "!!");
}
}
感谢您的帮助
【问题讨论】: