Spring autowire接口 [英] Spring autowire interface

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

问题描述

我有一个接口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

}

有没有办法只使用IMenuItem接口从配置类创建多个MenuItem实例?用@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配置文件。关于使用qulifiers和autowiring的好教程可以在这里找到。

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 autowire接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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