![](/img/trans.png)
[英]How do I call another Singleton bean from a Singleton bean?
[英]How do I access ArrayList in ApplicationScope bean from RequestScope bean
我正在嘗試從javax.enterprise.context.RequestScoped
bean訪問javax.enterprise.context.ApplicationScope
bean中的ArrayList<String>
。 我需要在部署時初始化AS Bean,因此我使用@javax.ejb.Singleton @javax.ejb.Startup
bean來初始化AS Bean。 我可以看到正在創建的數組,但是當我從RS bean訪問它時,它為null。 我在AS bean中有@PreDestroy
,它可以打印出數組的內容。 調用@PreDestroy時,該數組為null。 變量是否在AS Bean中持久存在?
@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
裝飾的方法中調用此方法。 看起來您需要使用@PostConstruct
裝飾simpleTest
:
@PostConstruct
public void simpleTest() {
//...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.