jsfmanaged-bean

Correct way of retrieving another bean instance from context


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?


Solution

  • 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:


    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.