Chris
Chris

Reputation: 3688

Gaining access to an already created`EJB from a View Scoped Managed Bean

In my web project, I have these components:

  1. EJB annotated class UserService
  2. EJB annotated class UserDAOImpl
  3. SessionScoped Managed Bean called UserStateBean
  4. ViewScoped ManagedBean called AdminDashboardView

The EJB UserService, is created at the init method (that is annotated with PostConstruct) of the UserStateBean and the UserDAOImpl is created at the init method of UserService, likewise.

Questions:

  1. Are these EJB classes stateless? (Haven't used any annotation above it, except for @EJB) If not, should they be?
  2. At the AdminDashboardView, I need to access the UserService EJB. Which is the proper way of doing that?

What I've already tried for (2):
At the AdminDashboardView, I declared it as a member, like this:

@EJB
private UserService userService;

At the init function I have this: userService = new UserService();.
This worked just fine, and succeeded with what I wanted to do, but, is this the correct way of doing that?

My thoughts on this, is that it could be correct, as the new instance of the UserService EJB I get, is from a pool that the container has (source). Is this correct?

Upvotes: 0

Views: 339

Answers (1)

BalusC
BalusC

Reputation: 1108722

Absolutely not!

You aren't supposed to create EJBs yourself like as that you aren't supposed to create JSF/CDI managed beans yourself. What you've there is a manually created and managed instance completely outside control of EJB container. If the EJB class in turn contained a @PersistenceContext, or another @EJB, then it would stay null, etc. Also that manually created instance has totally no notion of proxying and transaction management. The new works this way exactly like inside a main() method.

Put @Stateless on the EJB class and get rid of manual creation in @PostConstruct. The @EJB basically already injects it (like as that a @Inject basically already injects any @Named). The @EJB supports injecting of @Stateless, @Stateful and @Singleton classes.

See also:

Upvotes: 3

Related Questions