JSF 生命周期阶段顺序

JSF lifecycle phase order

我制作了小型 jsf 应用程序并且对生命周期顺序有点困惑,即使我在每次请求时都创建了该对象,但我在回发时遇到了意外的 NPE。有人可以解释幕后发生的事情吗?这是代码:

Entity.java

public class Entity {

    private Long id;
    private String property;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getProperty() {
        return property;
    }

    public void setProperty(String property) {
        this.property = property;
    }
}

Bean.java

import javax.enterprise.inject.Model;

@Model
public class Bean {

    private Long id;
    private Entity entity;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Entity getEntity() {
        return entity;
    }

    public void loadEntity() {
        this.entity = new Entity();
    }
}

edit.xhtml

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core"
      xmlns:o="http://omnifaces.org/ui">
    <f:view transient="true">
        <f:metadata>
            <f:viewParam name="id" value="#{bean.id}"/>
            <f:viewAction onPostback="true" action="#{bean.loadEntity()}"/>
        </f:metadata>
        <h:body>
            <o:form useRequestURI="true">
                <h:inputText value="#{bean.entity.property}"/>
                <h:commandButton value="Save"/>
            </o:form>
        </h:body>
    </f:view>
</html>

<f:viewAction action>这样的操作方法在调用应用程序阶段被调用。模型值在更新模型值阶段更新。因此,创建实体的阶段太晚了,当 属性 需要设置时仍然 null

摆脱 <f:viewAction> 并改为使用 @PostConstruct 方法。

@PostConstruct
public void init() {
    this.entity = new Entity();
}