Spring自动装配接口 [英] Spring autowire interface

查看:22
本文介绍了Spring自动装配接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接口 IMenuItem

I have an Interface IMenuItem

public interface IMenuItem {

    String getIconClass();
    void setIconClass(String iconClass);

    String getLink();
    void setLink(String link);

    String getText();
    void setText(String text);

}

然后我有这个接口的实现

Then I have a implementation for this interface

@Component
@Scope("prototype")
public class MenuItem implements IMenuItem {

    private String iconClass;
    private String link;
    private String text;

    public MenuItem(String iconClass, String link, String text) {
        this.iconClass = iconClass;
        this.link = link;
        this.text = text;
    }

    //setters and getters

}

有没有什么办法可以从一个配置类创建多个 MenuItem 实例,只使用 IMenuItem 接口?用@autowired 什么的?也可以通过指定构造函数的参数来自动装配吗?

Is there any way to create multiple instances of MenuItem from a configuration class, using only the IMenuItem interface? with @autowired or something ? Also is it possible to autowire by specifying the arguments of the constructor ?

推荐答案

@Autowired 实际上非常适合这种情况.您可以自动装配特定的类(实现)或使用接口.

@Autowired is actually perfect for this scenario. You can either autowire a specific class (implemention) or use an interface.

考虑这个例子:

public interface Item {
}

@Component("itemA")
public class ItemImplA implements Item {
}

@Component("itemB")
public class ItemImplB implements Item {
}

现在,您只需根据 @Component 注释值为对象选择一个名称,即可选择使用其中的哪一个实现

Now you can choose which one of these implementations will be used simply by choosing a name for the object according to the @Component annotation value

像这样:

@Autowired
private Item itemA; // ItemA

@Autowired
private Item itemB // ItemB

为了多次创建同一个实例,你可以使用@Qualifier注解来指定将使用哪个实现:

For creating the same instance multiple times, you can use the @Qualifier annotation to specify which implementation will be used:

@Autowired
@Qualifier("itemA")
private Item item1;

如果您需要使用某些特定的构造函数参数来实例化项目,则必须将其指定为 XML 配置文件.可以在这里找到关于使用限定符和自动装配的很好的教程.

In case you need to instantiate the items with some specific constructor parameters, you will have to specify it an XML configuration file. Nice tutorial about using qulifiers and autowiring can be found HERE.

这篇关于Spring自动装配接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆