Java Spring自动装配接口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31138830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring autowire interface
提问by adi.neag
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? with @autowired or something ? Also is it possible to autowire by specifying the arguments of the constructor ?
有什么方法可以仅使用 IMenuItem 接口从配置类创建 MenuItem 的多个实例?用@autowired 还是什么?也可以通过指定构造函数的参数来自动装配吗?
采纳答案by Smajl
@Autowired
is actually perfect for this scenario. You can either autowire a specific class (implemention) or use an interface.
@Autowired
实际上非常适合这种情况。您可以自动装配特定的类(实现)或使用接口。
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. Nice tutorial about using qulifiers and autowiring can be found HERE.
如果您需要使用某些特定的构造函数参数来实例化项目,则必须将其指定为 XML 配置文件。可以在这里找到关于使用限定符和自动装配的很好的教程。
回答by Bhupi
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
annotation 。
@Autowired
@Qualifer("MenuItem")
private IMenuItem menuItem
this will also create multiple instances
这也将创建多个实例