【问题标题】:spring - autowiring interface in abstract class with scope prototype does not workspring - 具有范围原型的抽象类中的自动装配接口不起作用
【发布时间】:2018-09-27 15:55:35
【问题描述】:

我有一个example spring project,我有一个抽象类Athlete,我想在其中自动装配一个接口Trainer

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

当我在Sprinter(扩展Athlete)中调用perform() 时,我想自动连接到AthleteTrainer 实例仍然为空

运动员:

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

感谢您的帮助

【问题讨论】:

    标签: java spring autowired


    【解决方案1】:

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

    运动员 a1 = new Sprinter("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);
    }
    

    【讨论】:

      【解决方案2】:

      您正在尝试使用非默认构造函数(带参数的构造函数)创建 bean 对象。您可以在类中声明默认构造函数,或者如果您真的想使用非默认构造函数创建 bean 实例,那么您可以这样做。

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

      【讨论】:

        猜你喜欢
        • 2013-11-02
        • 2013-01-29
        • 1970-01-01
        • 2019-05-19
        • 2019-02-22
        • 1970-01-01
        • 1970-01-01
        • 2012-11-27
        • 2017-03-15
        相关资源
        最近更新 更多