Correct way of retrieving another bean instance from context [duplicate]
We are using the following code to get the managed bean instance from the context.
FacesUtils.开发者_开发知识库getManagedBean("beanName");
Is it the correct way of doing it?. If multiple users access the same bean what will happen? How the bean instances are managed?
Since FacesUtils
is not part of standard JSF implementation, it's unclear what it is actually doing under the covers.
Regardless, when you're already inside a managed bean, then the preferred way is to inject the other bean as managed property. I'll assume that you're already on JSF 2.0, so here's a JSF 2.0 targeted example.
@ManagedBean
@SessionScoped
public void OtherBean {}
@ManagedBean
@RequestScoped
public void YourBean {
@ManagedProperty("#{otherBean}")
private void OtherBean;
@PostConstruct
public void init() {
otherBean.doSomething(); // OtherBean is now available in any method.
}
public void setOtherBean(OtherBean otherBean) {
this.otherBean = otherBean;
}
// Getter is not necessary.
}
But when you're still on JSF 1.x, then you need to do it by <managed-property>
entry in faces-config.xml
as explained in this question: Passing data between managed beans.
If you happen to use CDI @Named
instead of JSF @ManagedBean
, use @Inject
instead of @ManagedProperty
. For this, a setter method is not required.
See also:
- Communication in JSF2
- Get JSF managed bean by name in any Servlet related class
- Backing beans (@ManagedBean) or CDI Beans (@Named)?
As to your concern
If multiple users access the same bean what will happen? How the bean instances are managed?
They are managed by JSF. If a bean is found, then JSF will just return exactly this bean. If no bean is found, then JSF will just auto-create one and put in the associated scope. JSF won't unnecessarily create multiple beans.
精彩评论