@PostConstruct method is called even if the ManagedBean has already been instantiated (e.g. on AJAX-calls) [duplicate]

StackOverflow https://stackoverflow.com/questions/8804588

Question

I have a @ViewScope ManagedBean and a @PostConstruct initialisation method. This method is called when a new instance is created, but also on every ajax call. Why is this so?

On an AJAX-call the init-Method is called and executed, but no changes are visible. For example if I change a property in the init-Method, this is only visible on instatiation and not for AJAX-calls. For AJAX-calls the value change is not persistent in the @ViewScoped Bean.

Can anyone tell why this is so? How can I change this?

Was it helpful?

Solution

This is not normal behavior. This will happen if you bind tag handler attributes or the binding attribute of JSF components to a property of a view scoped bean while partial state saving is turned on. This is known as issue 1492 which is fixed in (the upcoming) Mojarra 2.2.

In general, you can recognize tag handlers by the lack of the rendered attribute. E.g. <c:if>, <f:validator>, <ui:include>, etc. If you bind an attribute of such a tag handler to a property of the view scoped bean like follows

<c:if test="#{viewScopedBean.something}"></c:if>
<h:inputText><f:validator binding="#{viewScopedBean.validate}" /></h:inputText>
<ui:include src="#{viewScopedBean.includePage}" />

then the view scoped bean will be recreated everytime the view is to be restored from a partially saved state. This is a chicken-egg issue with the view scope, because in order to get the right view scoped bean, it has to be extracted from the restored view.

This will also happen if you reference a property of a view scoped bean in the binding attribute of a JSF component.

<h:someComponent binding="#{viewScopedBean.someComponent}" />

See also:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top