【发布时间】:2021-04-13 06:52:06
【问题描述】:
我正在尝试使用包含 ArrayList 的 Java spring boot do Prototype 模式。我想实现拥有可以从任何地方访问的 ArrayList,对其进行修改。我得到了什么结果。每次清空ArrayList。
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE,proxyMode = ScopedProxyMode.TARGET_CLASS)
public class PrototypeBean {
private List<Long> listLong = new ArrayList<>();
public List<Long> getListLong() {
return listLong;
}
public void setListLong(List<Long> listLong) {
this.listLong = listLong;
}
public PrototypeBean() {}
public void printData() {
System.out.println("List size: " + listLong.size());
}
}
我怎么用这个?
class Calling {
@Lookup
public PrototypeBean get(){
return null;
}
private void buildList(){
List<Long> a = new ArrayList<>();
a.add(1L);
a.add(2L);
get().setListLong(a);
get().setListLong(a)
System.out.println(get().getListLong());
}
}
我也在尝试其他班级的设置列表
类构建列表 {
@Lookup
public PrototypeBean get(){
return null;
}
private void checkList(){
List<Long> a = new ArrayList<>();
a.add(1L);
a.add(2L);
get().setListLong(a);
get().setListLong(a)
System.out.println(get().getListLong());
}
每个请求我的列表大小始终为空。我希望我需要在同一个请求调用中从任何地方修改列表。
【问题讨论】:
-
@Scope(value = "request") -
prototype范围在访问时总是会返回一个新实例,这就是为什么你的列表总是空的原因 -
是的,总是返回带有新请求调用的新实例,但每个请求的所有生命周期都相同
-
这就是为什么你应该使用 bean 范围
request,而不是prototype -
谢谢,我会试试的。我有点迷路了......:D
标签: java spring spring-boot design-patterns