gpt4 book ai didi

java - 我可以使用 spring @Autowired 依赖注入(inject)来构建一个类的多个实例吗?

转载 作者:行者123 更新时间:2023-12-02 01:17:15 34 4
gpt4 key购买 nike

我有一个 vaadin UI 类,其构造函数采用 2 个参数。它使用一些字段构建一条简单的线,显示数据。在另一个(父)UI 中,我想多次嵌入第一个 UI(子),具体取决于父中加载的某些数据。所以现在我有两个问题:

  1. 我可以使用 springs @Autowired 注释将子 UI 的多个实例注入(inject)到父 UI 中吗?如果是,我该怎么做?
  2. 如何将参数传递给 @Autowired 子类的构造函数?

我已经发现,我必须用 @Autowired 注释我的子类的构造函数。

带有构造函数的我的子 UI 类(用 @Autowired 注释)

public class ChildUI {

private String arg1;
private String arg2;

@Autowired
public ChildUI(String arg1, String arg2){
this.arg1 = arg1;
this.arg2 = arg2;
}

}

在我的父类中,我想做这样的事情(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 注入(inject)了一些其他依赖项 - 首先将其设置为原型(prototype)范围,然后

    @Autowire
private ApplicationContext ctx;
....
for(Person p : personList){
ChildUI someChild=ctx.getBean(ChildUI.class,p.getLastName(),m.getFirstName());
}

关于java - 我可以使用 spring @Autowired 依赖注入(inject)来构建一个类的多个实例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58357386/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com