Staale
Staale

Reputation: 28008

Injecting into EJBs

I am trying to convert a Guice inject project to a Java EE project, that is to run on glassfish.

I have a lib project, that defines an interface, Hello, annotated with @Remote. Then I have an impl project that has a bean, HelloBean, annotated with @Stateless, and a single constructor with parameters and @Inject.

Then I have a was project that depends on the lib and it's interface to create a webservice, HelloService, annotated with @WebService, and Hello as a member annotated with @EJB.

This does not seem to work. Since beans must have a no-args constructor, I created HelloBean as a bean, and HelloImpl as a Pojo with a single @Inject constructor, with arguments. I have tried then injecting Hello and HelloImpl into HelloBean with both @Inject, @Resource and @EJB. None seem to work.

If I @Inject Hello or HelloImpl into HelloBean, I get a NPE. If I @Resource Hello or HelloImpl, I get an Lookup failed for delegate. If I @EJB HelloImpl, same error. @EJB Hello and I get stackoverflows (understandably).

I do want to use constructor injection, as I feel it's a more correct way of creating classes (they are always valid once constructed). But I don't see how it's possible to combine CDI and EJBs.

How can I get a Pojo with an @Inject constructor into a bean? Or is my plan fundamentally flawed?

Upvotes: 1

Views: 263

Answers (1)

LightGuard
LightGuard

Reputation: 5378

A better way is to define a initialize method annotated with @Inject. Any parameters will be injection points and should be supplied via CDI. You can also do this with constructors. Make sure you have WEB-INF/beans.xml as well.

Upvotes: 2

Related Questions