如何从RequestScope bean访问ApplicationScope bean中的ArrayList

时间:2013-11-08 19:58:08

标签: java cdi

我试图从ArrayList<String> bean访问javax.enterprise.context.ApplicationScope bean中的javax.enterprise.context.RequestScoped。我需要在部署时初始化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 */

1 个答案:

答案 0 :(得分:1)

您初始化ArrayList<String> apps的唯一位置是createApps方法,但这不会在类构造函数中调用,也不会在@PostConstruct修饰方法中调用。您似乎需要使用simpleTest

来装饰@PostConstruct
@PostConstruct
public void simpleTest() {
    //...
}