如何将单个类注释为两个不同的托管bean?

时间:2012-06-02 14:24:28

标签: jsf-2

我创建了一个地址bean,我想要使用它两次 - 一次用于街道地址,一次用于邮寄地址。我可以使用面部配置实现这一点,如下所示,但我想知道我是否可以通过注释来做到这一点。

e.g。把@ManagedBean(name =“StreetAddress”)和@ManagedBean(name =“MailingAddress”)放在同一个类上?我觉得我错过了一些明显的东西,但我不确定是什么。

<managed-bean>
    <managed-bean-name>MailingAddress</managed-bean-name>
    <managed-bean-class>com.leetb.jsf_ex1.model.AddressBean</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
    <map-entries/>
</managed-bean>
<managed-bean>
    <managed-bean-name>StreetAddress</managed-bean-name>
    <managed-bean-class>com.leetb.jsf_ex1.model.AddressBean</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
    <map-entries/>
</managed-bean>

public class AddressBean {

    private String line_one;
    private String line_two;
    private String suburb;
    private String state;
    private String postcode;

/* getters and setters snipped */
}

1 个答案:

答案 0 :(得分:1)

你有一个设计错误。那些看起来更像是模型类而不是支持bean类。模型类根本不应该是托管bean。使它们成为支持bean类的属性并改为管理它。

E.g。

@ManagedBean
@ViewScoped
public class AddressBacking {

    private AddressBean mailingAddress;
    private AddressBean streetAddress;

    @PostConstruct
    public void init() {
        // Prepare them here yourself. For example, when it's for a new entry.
        mailingAddress = new AddressBean();
        streetAddress = new AddressBean();
    }

    public void save() {
        // ...
    }

    // ...
}

(顺便说一下,我将AddressBean重命名为Address

并按如下方式使用

<h:inputText value="#{addressBacking.mailingAddress.line_one}" />
...
<h:inputText value="#{addressBacking.streetAddress.line_one}" />
...