[英]Can I use spring @Autowired dependency injection to build multiple instances of a class?
我有一个带有 2 个 arguments 的构造函数的 vaadin UI class。 它用一些字段构建了一条简单的线,显示数据。 在另一个(父) UI 中,我想多次嵌入第一个 UI(子),具体取决于父级中加载的一些数据。 所以现在我有两个问题:
@Autowired
注释将我的子 UI 的多个实例注入父级吗? 如果是,我该怎么做?@Autowired
子 class 的构造函数? 我已经发现,我必须用@Autowired
注释我的孩子 class 的构造函数。
我的孩子 UI class 带有构造函数(用@Autowired
注释)
public class ChildUI {
private String arg1;
private String arg2;
@Autowired
public ChildUI(String arg1, String arg2){
this.arg1 = arg1;
this.arg2 = arg2;
}
}
在我的父母 class 中,我想做这样的事情(personList 是从数据库加载的):
public class ParentUI {
...
for(Person p : personList){
//inject instance of ChildUI here and pass p.getLastName() to arg1 and p.getFirstName() to arg2
}
...
}
我用谷歌搜索了一段时间,但我并没有真正找到我想要的东西。 也许我只是不知道要搜索什么关键字。 也许有人可以尝试解释该怎么做?
像往常一样创建ChildUI
for(Person p : personList){
ChildUI someChild=nChildUI(p.getLastName(),m.getFirstName());
}
...
和someChild
或者如果ChildUI
注入了一些其他依赖项 - 首先使其原型作用域,然后
@Autowire
private ApplicationContext ctx;
....
for(Person p : personList){
ChildUI someChild=ctx.getBean(ChildUI.class,p.getLastName(),m.getFirstName());
}
我不确定我是否完全理解你的要求,所以如果这不是你的意思,请告诉我。
创建 childUI 的多个实例:这很简单,在配置 class 中创建多个 bean:
@Configuration
public class ApplicationConfiguration {
@Bean
public ChildUI firstBean(){
return new ChildUI(arg1,arg2);
}
@Bean
public ChildUI secondBean(){
return new ChildUI(otherArg1,otherArg2);
}
@Bean
public ChildUI thirdBean(){
return new ChildUI(arg1,arg2);
}
}
注入其他 bean 的多个实例:如果自动装配 bean 类型的集合(或列表),它的所有实例都将注入它:
public class ParentUI {
private final Set<ChildUI> children;
@Autowired
public ParentUI(Set<ChildUI> children) {
this.childern = children;//this will contain all three beans
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.