When should one use the f:viewAction or preRenderView event to initialize data for a page versus using the @PostConstruct annotation? Is the rationale to use one or the other based on the type of scope of the backing bean e.g. If the backing bean is @RequestScoped, then would the choice of using f:viewAction or preRenderView over @PostConstruct to initialize your backing bean prior to rendering the view be irrelevant as the two would result in the same effect?
f:viewAction or preRenderView
<f:metadata>
<f:viewAction action="#{myBean.initialize}" />
</f:metadata>
<f:metadata>
<f:event type="preRenderView" listener="#{myBean.initialize}"/>
</f:metadata>
or
@PostConstruct
public class MyBean
{
@PostConstruct
public void initialize()
{
}
}
Use the
<f:viewAction>when you want to execute a method before the HTML is been rendered. This is particularly useful if you want to perform actions based on model values set by<f:viewParam>during update model values phase. Namely, they are not available at the moment the@PostConstructruns. In JSF 2.0/2.1, this tag didn't exist and you have to use thepreRenderViewworkaround.No, they do definitely not effectively do the same thing. The
@PostConstructis intented to perform actions directly after bean's construction and setting of all injected dependencies and managed properties such as@EJB,@Inject,@ManagedProperty, etc. Namely, the injected dependencies are not available inside the bean's constructor. This will thus run only once per view, session or application when the bean is view, session or application scoped. The<f:viewAction>is by default only invoked on initial GET request, but can viaonPostback="true"attribute be configured to be invoked on postback requests as well. ThepreRenderViewevent is invoked on every HTTP request (yes, this also includes ajax requests!).Summarized, use
@PostConstructif you want to perform actions on injected dependencies and managed properties which are set by@EJB,@Inject,@ManagedProperty, etc during bean's construction. Use<f:viewAction>if you also want to perform actions on properties set by<f:viewParam>. If you're still on JSF 2.0/2.1, usepreRenderViewinstead of<f:viewAction>. You can if necessary add a check onFacesContext#isPostback()to perform thepreRenderViewaction on initial request only.See also: