Skip to main content

CDI gotcha

Posted by ljnelson on July 23, 2010 at 10:00 AM PDT

I learned this the hard way and wanted to make sure other people could benefit.

While putting together a Java EE 6 application, I had put together a @SessionScoped bean that inherited from an abstract superclass.  Both the super- and subclass have injection points.  The subclass uses @Inject; the superclass only uses @PersistenceContext.

Now, I had added the required META-INF/beans.xml file to the jar file housing the subclass, but never thought to add it to the superclass jar file, since of course when I wrote the superclass I wasn't thinking CDI at all (and actually as it happened when I wrote the abstract superclass it was in the Java EE 5 days), so why would I have packaged it into a bean archive?

But it turns out--somewhat unintuitively--that if you inherit from a class that has an injection point in it--even if the injection point is defined in terms of Java EE and not CDI--and if that abstract class comes from a jar that is not a bean archive, then dependency injection by the CDI provider will not be applied to its injection point until you make sure that its jar file contains a META-INF/beans.xml file.

A simpler way to put this is that for any given inheritance chain, all jars in the chain containing classes with injection points must be bean archives.

(On a totally unrelated subject, the documentation links in this post are to the horrific new documentation URLs that Oracle has seen fit to impose on the Java community landscape.  Add your voice to the general din calling for the old URLs to come back after checking out the Twitter E17476 hashtag.)

Related Topics >>

Comments

I'm pretty sure this is a bug

I'm pretty sure this is a bug in GlassFish, suggest you file an issue in their issue tracker.