开发者

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 'fo开发者_Go百科oBean' resolved to null

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


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).


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{
    //...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜