Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

java - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...