我正在尝试访问ArrayList<String>
位于 javax.enterprise.context.ApplicationScope
中来自 javax.enterprise.context.RequestScoped
的 bean bean 。我需要在部署时初始化 AS bean,因此我使用 @javax.ejb.Singleton @javax.ejb.Startup
bean 来初始化我的 AS bean。我可以看到正在创建的数组,但是当我从 RS bean 访问它时,它是空的。我有@PreDestroy
在打印出数组内容的 AS bean 中。当@PreDestroy被调用时,数组为空。变量是否会保留在 AS beans 中?
@Named("simpleTest")
@ApplicationScoped
public class SimpleTest implements Serializable{
private static final long serialVersionUID = -9213673463118041881L;
private ArrayList<String> apps;
public void simpleTest() {
createApps();
debugApps();
}
public void createApps() {
apps = new ArrayList<String>();
apps.add("This is string 1");
apps.add("This is string 2");
}
public void debugApps() {
System.out.println("Beginning debug...");
for (String a : apps){
System.out.println(a);
}
}
@PreDestroy
public void ending() {
System.out.println("Hey there, I'm about to destroy the SimpleTest Bean...");
debugApps();
}
/* Getters and setters */
...
RS bean :
@Named("aBean")
@RequestScoped
public class ABean implements Serializable{
private static final long serialVersionUID = -7213673465118041882L;
private ArrayList<String> myApps;
private String str;
@Inject
private SimpleTest st;
public void initStr(){
if (myApps != null){
for (String s : myApps){
setStr(s);
}
}
}
@PostConstruct
public void init(){
setMyApps(st.getApps());
initStr();
}
public String getErrs(){
String errs = "I couldn't find the apps";
if (myApps != null){
errs = "I found the apps!";
}
if (str != null){
errs = str;
}
return errs;
}
/* Getters and setters */
最佳答案
您初始化ArrayList<String> apps
的唯一地方位于createApps
方法,但这既没有在类构造函数中也没有在 @PostConstruct
中被调用装饰方法。看来你需要装饰一下simpleTest
与 @PostConstruct
:
@PostConstruct
public void simpleTest() {
//...
}
关于java - 如何从 Request Scope bean 访问 ApplicationScoped bean 中的 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19867538/