Search code examples
javajakarta-eeejb-3.0java-ee-6ejb-3.1

EJB 3.1 - Using @EJB inside an EJB - is it possible?


Is it possible to use @EJB inside another EJB? I'm trying to do this now, and my EJB is ending up null. I'll outline my problem in an example.

@Stateless
@LocalBean
@Local(LoginServiceLocal.class)
public class LoginService implements LoginServiceLocal {    

    public void createLogin(String email, String password) { ... }
}

@Stateless
@LocalBean
@Local(AccountServiceLocal.class)
public class AccountService implements AccountServiceLocal {

    @PersistenceContext(unitName = "accounts")
    private EntityManager accountEntityManager;

    @EJB
    private LoginServiceLocal loginService;

    public void createAccount(Account account, String email, String password) {
        accountEntityManager.persist(account);
        loginService.createLogin(email, password);
    }
}

Is this type of thing supposed to be possible? I should also mention that I'm using an embedded container (via EJBContainer), and I'm looking up the AccountService using JNDI, however when I try and call loginService.createLogin in the AccountService, the loginService is null (not being initialized by @EJB).

Is what I'm trying to do possible?

Thanks.


Solution

  • Yes, it's possible.

    The @LocalBean annotation, enables an EJB to expose a no-interface client view, so that you won't need to define a Local interface.

    On the other hand, the @Local annotation defines a bean's local client interface.

    Choose one of the above configuration options not both.

    If you choose to use the @LocalBean annotation, drop the @Local annotation, remove the implements keyword and inject the bean class name with the @EJB annotation.

    If you choose to use the @Local annotation, drop both @Local and @LocalBean annotations and inject the bean with the @EJB annotation using the interface name.