Tuukka Mustonen
Tuukka Mustonen

Reputation: 4831

JSF 2.0: Why does a JSF bean get created when it's used in a component that is not rendered?

Let's have an extremely simple composite component:

<cc:implementation>
    #{testBean.someField}
</cc:implementation>

Bean for it:

public class TestBean {

    private boolean someField = false;
    public boolean getSomeField() { return someField; }

    @PostConstruct
    public void init() {
        System.out.println("PostConstruct");
    }

}

Then call it as usual but don't show it:

<codeEditor:test rendered="#{false}" />

What happens is that the component is never rendered and the bean is never initiated as one would suppose.

However, if we change the component as:

<cc:implementation>
    <h:outputText value="#{testBean.someField}" />
</cc:implementation>

What happens is that the component still never gets rendered (because the rendered attribute is false), however, the bean does get instantiated. This happens always when we use a bean property inside some native JSF component (h:panelGroup, h:inputHidden, whatever).

Why is it so?

Upvotes: 3

Views: 721

Answers (1)

BalusC
BalusC

Reputation: 1108722

The components (and all of the bound beans) get created during view build time. The rendered attribute is only evaluated during view render time. It has always worked that way in JSF.

If the bean is doing some expensive job during construction, then I'd suggest to let that expensive job depend on the some condition which you then reuse in the rendered attribute.

Upvotes: 6

Related Questions