Tuesday, January 4, 2011

Monday, January 3, 2011

JSF beans getter with Spring AOP

Introduction

JSF can call a getter more than once per request.

For example in the following JSF file :

<html>
<body>
<h:dataTable var="car" value="#{carService.cars}">
<h:column>
<f:facet name="header">
Model
</f:facet>
<h:outputText value="#{car.model}"/>
</h:column>

<h:column>
<f:facet name="header">
Year
</f:facet>
<h:outputText value="#{car.year}"/>
</h:column>

<h:column>
<f:facet name="header">
Manufacturer
</f:facet>
<h:outputText value="#{car.manufacturer}"/>
</h:column>
</h:dataTable>
</body>
</html>

JSF will call the carService.cars getter more than once inside the same request.

In this example, JSF calls it three times :

13:39:40 DEBUG : CarService.getCars:17 - qtp17489534-18

13:39:40 DEBUG : CarService.getCars:17 - qtp17489534-18

13:39:40 DEBUG : CarService.getCars:17 - qtp17489534-18

A getter obviously returns a value. This value can be a bean property or a calculated value.

If the value is calculated, this can potentially be a problem.

I googled a bit and found some workarounds.

  1. The first one was to include a check and see if it has already been calculated.
  2. The second one was to use the getter only to access bean properties
  3. The third one was to use Spring AOP and cache the value.


For me, the last workaround is the best one because you do not have to modify the view.

And thanks to Spring, it's quite simple to add AOP with a few annotations.