I am trying to build a simple blog on JSF. However, I do not know how to inject same stateful ejb instance into 2 different managed beans. I know that injecting could be done indirectly, by using @ManagedProperty annotation. Something like that:
@ManagedBean
@ViewScoped
public class PostController implements Serializable {
private static final long serialVersionUID = 1L;
private Post temporaryPost;
@ManagedProperty(value = "#{authenticationController}")
private AuthenticationController authenticationController;
@Inject
private PostEJB postEJB;
public void save() {
getTemporaryPost().setAuthor(
getAuthenticationController().getAuthenticationEJB()
.getCurrentSessionUser());
postEJB.create(getTemporaryPost());
}
}
I want to get rid of
@ManagedProperty(value = "#{authenticationController}") private AuthenticationController authenticationController;
and inject AuthenticationEJB directly, like
@Inject private AuthenticationEJB authenticationEJB;
So, instead of
getAuthenticationController().getAuthenticationEJB() .getCurrentSessionUser()
I will get
authenticationEJB.getCurrentSessionUser()
But, the problem is that this is new authenticationEJB instance, which do not contain currently logged in user(User is null). At the same time authenticationController.authenticationEJB.currentsessionuser contains logged in user.
Thanks in advance!
Finnaly got the answer! It is easy:
@ManagedProperty(value = "#{authenticationController.authenticationEJB}")
private AuthenticationEJB authenticationEJB;
Now it points to the same authenticationEJB instance. However, I believe there might be some other ways to do it.
Well, you got the answer but maybe couple of notes
PostController
with @EJB
annotation?CDI beans
instead of JSF Managed Beans, they will soon get deprecated (and whole Java EE stack is slowly moving towards using CDI everywhere)@ManagedProperty
, every bean (which will basically be any class in your application) will get injectable with @Inject
annotation. Same thing applies for EJBs, so CDI kind of unifies the access to most types of beans.