Adam Bien's Weblog

@Inject vs. @EJB

You can use both annotations to inject EJBs. Start with @Inject and if you encounter any problems, switch to @EJB.

@Inject does not have any methods / attributes--it is just a plain annotation:

@Target(value = {ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Inject {

On the other hand, the @EJB annotation allows you to pass additional information, which could be useful to reference remote EJBs, or EJBs which cannot be simple injected in the "Convention over Configuration" style:

@Target(value = {ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface EJB {

    public String name() default "";

    public String beanName() default "";

    public Class beanInterface() default Object.class;

    public String mappedName() default "";

Sometimes (e.g. for exposure of as JMX managed bean) it may be necessary to use a "self" reference to an EJB. You could inject a reference to "self" with @EJB, but not @Inject.

See also an in-depth discussion in the "Real World Java EE Patterns--Rethinking Best Practices" book (Second Iteration, "Green Book"), page 411 in, chapter "Self-Invoking Beans"

See you at Java EE Workshops at MUC Airport (March 25th-28th)!

Summer Workshops: From Java EE 7 Bootstrap and Effective Java EE 7 to Java EE 7 Architectures


A book about rethinking Java EE Patterns


Hi Adam,

Is it possible to pass additional custom configuration to an EJB, ie. @EJB(foo=bar) ? If not, is it possible to create an EJB via a @Producer method that performs some configuration upon creation?


Posted by David Boman on November 09, 2012 at 07:56 PM CET #

Be careful with Weblogic 12 and @Decorator for EJBs. In our case it works only with @Inject but not with @EJB.

Posted by on November 09, 2012 at 09:54 PM CET #

Hi Adam,

Thanks for this clear explanation! This was exactly what I was wondering... when to use what.
However if you're building portlets for liferay you cannot use the CDI (adding the beans.xml gives you a WeldException). So here you have to use the @EJB.


Posted by Ivar on November 15, 2012 at 11:11 PM CET #

Hi Adam,

Thx for explaining when @EJB can be useful.
But when using it, you're coupling the injection point (business interface) with the implementation type (it's an EJB).

Posted by JLM on December 12, 2012 at 10:23 AM CET #

It would be very interesting if the last question was answered.

Posted by San on January 30, 2014 at 05:36 PM CET #

Very simple and clear explanation. Thanks!

Posted by Chris on February 11, 2015 at 01:32 AM CET #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments