This week's book giveaway is in the Android forum.
We're giving away four copies of Head First Android and have Dawn & David Griffiths on-line!
See this thread for details.
The moose likes EJB and other Java EE Technologies and the fly likes NullPointer when working with Events in CDI Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Java » EJB and other Java EE Technologies
Bookmark "NullPointer when working with Events in CDI" Watch "NullPointer when working with Events in CDI" New topic

NullPointer when working with Events in CDI

Joe carco
Ranch Hand

Joined: Apr 14, 2009
Posts: 82

my problem concerns the following code

This ApplicationScoped Named Bean is accessed mainly from a Facelet using JSF 2.0. It is ApplicationScoped becuase the data it holds is fairly small and is only very rarely updated. So whenever a "Status" is changed, I fire an Event<Status> from the class that changes it via a CRUD operation. When the StatusBackingBean is initially created and the @PostConstruct method is called, obviously the statusFacade (a StatelessSessionBean) in correctly injected and is not null. When the event fires when a "Status" object is changed, I want to reload all the statuses from the database, so that all users have a freshly updated list of Statuses. However when calling statusFacade.findAll(); in the method private void statusChanged(@Observes Status status) I get a NullPointerException stating that the StatusFacade is null.

Is it not true that in an ApplicationScoped Bean, injected Enterprise Beans should always have a reference to a valid instance. Why is it NULL when accessed for a second time when the statusChanged method is fired even though it is the same object every time? is the injected StatusFacade instance nulled right after the method annotated with "PostConstruct" returns?

I am using GlassFish 3 (with WELD), NetBeans 3.9.1
Joe carco
Ranch Hand

Joined: Apr 14, 2009
Posts: 82
Ok I think I've got this one figured out:

Only a reference to the StatusBackingBean that is injected via CDI has a valid reference to the StatusFace SLSB, even though the object hashcode of the StatusBackingBean is the same throughout the entire Application. Seems to me that only the Proxy Object created when Injecting via CDI has an initialized Statusfacade an List of Statuses. It seems to me as if accessing any Field from the statusChanged method when the Event fires causes a NullPointerException because it is a different ProxyObject.

So this is what I did:

... works like a charm :-)
I agree. Here's the link:
subject: NullPointer when working with Events in CDI
jQuery in Action, 3rd edition