Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 502
elisman Avatar asked Jan 10 '12 13:01

elisman


People also ask

How many times a @PostConstruct method is called?

2. @PostConstruct. Spring calls the methods annotated with @PostConstruct only once, just after the initialization of bean properties.

What is PostConstruct in JSF?

The @PostConstruct annotation is a lifecycle hook, meaning that it allows the developer to tap into the JSF component lifecycle. The PostConstruct informs JSF to run this code once the component has been constructed, but before it has been rendered.


1 Answers

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:

  • Communication in JSF 2.0 - @ViewScoped fails in tag handlers
like image 84
BalusC Avatar answered Sep 30 '22 00:09

BalusC