0

What is an Application Scoped Bean? I understand it to be a bean which will exist for the life of the application, but that doesn't appear to be the correct interpretation. I have an application which creates an application scoped bean on startup (eager=true) and then a session bean that tries to access the application scoped bean's objects (which are also application scoped). But when I try to access the application scoped bean from the session scoped bean, I get a null pointer exception. Here's excerpts from my code:

Application Scoped Bean:

    @ManagedBean(eager=true)
    @ApplicationScoped
    public class Bean1 implements Serializable{
      private static final long serialVersionUID = 12345L;
      protected ArrayList<App> apps;
      // construct apps so they are available for the session scoped bean
      // do time consuming stuff...
      // getters + setters

Session Scoped Bean:

   @ManagedBean
   @SessionScoped
   public class Bean2 implements Serializable{
     private static final long serialVersionUID = 123L;

     @Inject
     private Bean1 bean1;
     private ArrayList<App> apps = bean1.getApps();  // null pointer exception

What appears to be happening is, Bean1 is created, does it's stuff, then is destroyed before Bean2 can access it. I was hoping using application scoped would keep Bean1 around until the container was shutdown, or the application was killed, but this doesn't appear to be the case.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
taylordurden
  • 357
  • 2
  • 5
  • 17

1 Answers1

2

Your first line is correct:

a bean which will exist for the life of the application.

However, you cannot access an injected resource in a constructor, as it may not be available yet. Your initialization line: private ArrayList<App> apps = bean1.getApps(); is run during object construction.

Instead, access the resource in a method marked by a @PostConstruct annotation:

@ManagedBean
@SessionScoped
public class Bean2 implements Serializable{
    private static final long serialVersionUID = 123L;

    @Inject
    private Bean1 bean1;
    private ArrayList<App> apps;


    @PostConstruct
    private void init() {
        apps = bean1.getApps();
    }
}
Kevin
  • 4,070
  • 4
  • 45
  • 67