What is the difference between @Inject and @EJB

让人想犯罪 __ 提交于 2019-11-28 05:44:17
  1. @EJB injects EJBs only, but @Inject can be used to inject POJOs rather than EJBs. However, @Inject requires that your archive be a BDA (contain beans.xml for EE 6, or implicitly in EE 7). @Inject also has additional CDI-specific capabilities (scopes, interceptors, etc.), but those capabilities incur extra overhead. Application servers have support for specifying @EJB bindings so that a deployer can choose the target EJB, but @Inject only allows the application developer to choose the target EJB (and it must exist in the application).

  2. If the target is not an EJB, then you must not use @EJB.

  3. It depends whether you're making multiple inter-related queries and then attempting to make business decisions. You need to understand isolation levels and take them into consideration, even for read-only operations.

Pramod Alagambhat

From Adam Biens Weblog:

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)
@Documented
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 "";
}
  1. @Inject is more general than EJB and is part of CDI specification. So if you want to use @Inject, you need an implementation of it in your server.

  2. For POJOs (not EJBs) you have to use @Inject.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!