JSF 2:是否可以继承@ManagedBean? [英] JSF 2 : Is it possible to inherit @ManagedBean?

查看:119
本文介绍了JSF 2:是否可以继承@ManagedBean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Bean ,其中包含 @ 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;

}

现在,我有另一个定义如下的bean:

Now, I have another bean defined like this :


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



当我尝试在我的JSF页面中引用FooBean时,我有以下错误:

目标无法访问,标识符'fooBean'已解析为空

为什么选择JSF没有看到 FooBean 作为托管bean?

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

推荐答案

重点亚历克斯试图让你把类与实例混淆。这是一个经典的(双关语)OOP错误。

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

@ManagedBean注释不适用于类本身。它适用于此类的实例,定义了托管的实例。

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

如果您的bean定义如下:

If your bean is defined like this:

@ManagedBean
@SessionScoped
public class MyBean implements Serializable {

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

那么这意味着你有一个会话范围的实例,称为myBean(或任何你想要命名的东西)。

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

因此,不管理作为MyBean 的子类的所有类默认。此外,JSF如何识别您使用子类的位置?如果是这样,你给这些实例的名字是什么? (因为你必须给他们一些名字,否则,JSF将如何管理他们?)

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

@PostConstruct和您使用的所有其他注释会发生什么?没有。如果您创建了MyBean的实例,则由您管理它,而不是JavaServerFaces。所以它不是真正的托管bean,只是你使用的常见对象。

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() { ... }
}

然后,托管的不是类,而是类的实例。拥有ManagedBean意味着您只有该bean的一个实例(每个范围,即)。

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

这篇关于JSF 2:是否可以继承@ManagedBean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆