簡體   English   中英

spring-具有范圍原型的抽象類中的自動裝配接口不起作用

[英]spring - autowiring interface in abstract class with scope prototype does not work

我有一個春季項目示例 ,其中有一個抽象類的Athlete ,我想將接口Trainer自動連接到其中。

AthleteRunnable和其實施方式中覆蓋一個perform()方法。

當我在Sprinter調用perform() (擴展Athlete )時,我想自動連線到AthleteTrainer實例仍然為null

運動員:

@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 + "!!");
    }
}

謝謝您的幫助

在我的主要班級中,您正在親自創建這些對象。

運動員a1 =新短跑選手(“ adam”);

Spring只能將對象自動裝配到(托管的)Bean中。 在這一點上,Spring根本不知道您創建的Sprinter實例甚至存在。

當讓Spring為您創建bean時,它還將注入所有@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);
}

您正在嘗試使用非默認構造函數(帶參數的構造函數)創建bean對象。 您可以在類中聲明默認構造函數,或者如果您確實想使用非默認構造函數創建bean實例,則可以執行以下操作。

https://dzone.com/articles/instanciating-spring-component

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM