Pregunta

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.

¿Fue útil?

Solución

Well, you got the answer but maybe couple of notes

  • why won't you inject your bean directly to PostController with @EJB annotation?
  • If you develop a new project, use CDI beans instead of JSF Managed Beans, they will soon get deprecated (and whole Java EE stack is slowly moving towards using CDI everywhere)
  • then you can get rid of @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.
  • some basic CDI + JSF tutorial here
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top