3

I am going through JavaEE7-samples repo in github. I found that the author has mentioned the following in this code snippet:

// Cannot be injected using @Inject
@EJB Cart bean;

The author explicitly mentions that @Inject will not work. But I am wondering what is the reason behind it?

I have read the following posts on difference between @EJB and @Inject. but that did not help me here.

http://www.adam-bien.com/roller/abien/entry/inject_vs_ejb

What is the difference between @Inject and @EJB

Should I use @EJB or @Inject

Community
  • 1
  • 1
brain storm
  • 30,124
  • 69
  • 225
  • 393

1 Answers1

3

Both will work if the bean has Local interface. However for @Inject to work you have to enable CDI (create beans.xml file in your WEB-INF folder).

If the bean has Remote interface you would need to have producer class to declare the resource with the following code:

public class RemoteProducer {
    @Produces @EJB
    HelloRemote helloBean;
}

For more details see section 3.5 in the JSR-299 CDI specification.
So for simplicity of usage I'd suggest to stick with @EJB for EJBs.

Gas
  • 17,601
  • 4
  • 46
  • 93
  • I guess you dont need beans.xml in Java EE 7 container which is what I am using. – brain storm Oct 01 '14 at 23:56
  • @brainstorm Ahh, you might be right. I've tested it in Java EE 6 container. – Gas Oct 02 '14 at 00:01
  • and the javaee7-samples link above is tested against javaee7. so I still don't get the point why @Inject will not work.. – brain storm Oct 02 '14 at 00:16
  • @brainstorm Except beans.xml that can be optional in certain cases in Java EE 7, rest of the answer stands. You can check the CDI 1.1 spec (jsr-346) - For `Remote` EJB you need Producer field or method. – Gas Oct 02 '14 at 06:30