Brian DiCasa
Brian DiCasa

Reputation: 9487

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.

Upvotes: 4

Views: 3559

Answers (3)

Armen Arzumanyan
Armen Arzumanyan

Reputation: 2043

If you are used EJB3.1 you can also use @Inject from CDI

Upvotes: 1

dimsap
dimsap

Reputation: 36

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.

Upvotes: 2

JOTN
JOTN

Reputation: 6317

Yes, I was just working on some of my code that does just that. It might be an issue with how you're creating the EJB. I have only done it using injection and not a jndi lookup.

Upvotes: 1

Related Questions