0

我正在尝试从一个 bean 访问一个 bean 中的ArrayList<String>一个。我需要在部署时初始化 AS bean,所以我使用bean 来初始化我的 AS bean。我可以看到正在创建的数组,但是当我从 RS bean 访问它时,它为空。我在打印出数组内容的 AS bean 中。调用 @PreDestroy 时,数组为空。变量是否保留在 AS bean 中?javax.enterprise.context.ApplicationScopejavax.enterprise.context.RequestScoped@javax.ejb.Singleton @javax.ejb.Startup@PreDestroy

@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豆:

@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 */
4

1 回答 1

1

您初始化的唯一地方ArrayList<String> apps是在createApps方法中,但这既不是在类构造函数中调用,也不是在@PostConstruct装饰方法中。看起来你需要simpleTest装饰@PostConstruct

@PostConstruct
public void simpleTest() {
    //...
}
于 2013-11-08T20:04:00.880 回答