简体   繁体   English

Spring autowire接口

[英]Spring autowire interface

I have an Interface IMenuItem 我有一个接口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

}

Is there any way to create multiple instances of MenuItem from a configuration class, using only the IMenuItem interface? 有没有办法只使用IMenuItem接口从配置类创建多个MenuItem实例? with @autowired or something ? 用@autowired还是什么? Also is it possible to autowire by specifying the arguments of the constructor ? 也可以通过指定构造函数的参数来自动装配?

@Autowired is actually perfect for this scenario. @Autowired实际上非常适合这种情况。 You can either autowire a specific class (implemention) or use an interface. 您可以自动装配特定类(实现)或使用接口。

Consider this example: 考虑这个例子:

public interface Item {
}

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

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

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 现在,您可以根据@Component注释值选择对象的名称,从而选择使用这些实现中的哪一个

Like this: 像这样:

@Autowired
private Item itemA; // ItemA

@Autowired
private Item itemB // ItemB

For creating the same instance multiple times, you can use the @Qualifier annotation to specify which implementation will be used: 要多次创建同一实例,可以使用@Qualifier批注指定将使用的实现:

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

In case you need to instantiate the items with some specific constructor parameters, you will have to specify it an XML configuration file. 如果您需要使用某些特定的构造函数参数实例化项目,则必须将其指定为XML配置文件。 Nice tutorial about using qulifiers and autowiring can be found HERE . 关于使用qulifiers和autowiring的好教程可以在这里找到。

i believe half of job is done by your @scope annotation , if there is not any-other implementation of ImenuItem interface in your project below will create multiple instances 我相信有一半的工作是由你的@scope注释完成的,如果你的项目中没有任何其他ImenuItem接口的实现将创建多个实例

@Autowired
private IMenuItem menuItem

but if there are multiple implementations, you need to use @Qualifer annotation . 但如果有多个实现,则需要使用@Qualifer注释。

@Autowired
@Qualifer("MenuItem")
private IMenuItem menuItem

this will also create multiple instances 这也将创建多个实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM