Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSF 2 : Is it possible to inherit @ManagedBean?

I have a Bean ,with a @ManagedBean annotation, defined like this :


@ManagedBean
@SessionScoped
public class Bean implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

}

Now, I have another bean defined like this :


public class FooBean extends Bean {
    // properties, methods here ...
}


When I try to reference FooBean in my JSF page, I have the following error :
Target Unreachable, identifier 'fooBean' resolved to null

Why JSF doesn't see FooBean as a managed bean ?

like image 319
Stephan Avatar asked Jul 08 '11 16:07

Stephan


2 Answers

The point Alex is trying to make is that you're confusing classes with instances. This is a classic (pun intended) OOP mistake.

The @ManagedBean annotation does not work on classes per-se. It works on instances of such classes, defining an instance that is managed.

If your bean is defined like this:

@ManagedBean
@SessionScoped
public class MyBean implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
}

Then it means you have a session-scoped instance, called myBean (or whatever you want to name it).

Therefore, all classes that are subclasses of the MyBean class are not managed by default. Furthermore, how does JSF recognize where you're using the subclasses? If so, what names are you giving to those instances? (Because you have to give them some name, otherwise, how would JSF manage them?)

So, let's say you have another class:

Class MyOtherClass {
    private MyBean myBeanObject; // myBeanObject isn't managed. 
}

what happens to the @PostConstruct and all the other annotations you used? Nothing. If you created the instance of MyBean, then it's YOU who manages it, not JavaServerFaces. So it's not really a managed bean, just a common object that you use.

However, things change completely when you do this:

@ManagedBean
@SessionScoped
Class MyOtherClassBean {
    @ManagedProperty("#{myBean}")
    private MyBean myBeanObject;

    public void setMyBeanObject(...) { ... }
    public MyBeanClass getMyBeanObject() { ... }
}

Then again, what is managed is not the class, but the instance of the class. Having a ManagedBean means that you only have one instance of that bean (per scope, that is).

like image 72
Rick Garcia Avatar answered Oct 22 '22 15:10

Rick Garcia


do you need BaseBean to be a managed bean? Since you name it BaseBean, I assume that this bean hold commonality between all your other managed bean. If so then it should not contain @ManagedBean annotation. Do this

public abstract BaseBean{
    //...
}

Then inside your managed bean

@ManagedBean
@RequestScoped
public class FooBean extends BaseBean{
    //...
}
like image 27
Thang Pham Avatar answered Oct 22 '22 16:10

Thang Pham