如何在子类中将@Autowired用于基类中定义的字段?

时间:2019-05-02 15:19:20

标签: spring interface abstract-class subclass autowired

是否可以为子类中的实例自动关联基类中定义的字段?

所以, 界面:

public interface Xyz { ...}

抽象基类:

public abstract class Abc {
    Xyz xyz;
}

我要自动装配接口的具体实现的抽象类的子类:

public class Def extend Abc {
    @Autowired
    // Here I want to autowire a concrete implementation of Xyz, maybe called XyzImpl. Can I do this maybe in a constructor or ...?
}

public class Ghi extend Abc {
    @Autowired
    // Here I want to autowire a concrete implementation of Xyz, maybe called XyzImpl. Can I do this maybe in a constructor or ...?
}

public class Jkl extend Abc {
    @Autowired
    // Here I want to autowire a concrete implementation of Xyz, maybe called XyzImpl. Can I do this maybe in a constructor or ...?
}

1 个答案:

答案 0 :(得分:1)

尝试一下:

  1. Abc类中,进行此更改private final Xyz xyz;
  2. Abc类中,添加一个带有Xyz参数的构造函数;在此构造函数中设置xyz字段。
  3. Def类中,添加一个带有Xyz参数并调用super(xyz)的构造函数。
  4. 自动装配xyz构造函数中的Def参数。