MaikoID
MaikoID

Reputation: 5007

JSF 2 @PostConstruct method called twice

I've got a strange behavior: my method annotated with @PostConstruct is called twice.

Debugging it, I saw that my search page called it before the command link's action methos mbean.edit was called. My bean MBeanSearch is request scoped, my MBean is view scoped.

My view search.xhtml:

<h:commandLink value="#{var.value}" action="#{mbean.edit}">
    <f:param name="id" value="#{var.id}"/>
</h:commandLink>

I've also got a target view var.xhtml.

Relevant extract from my MBean bean:

    public String edit() {
        return "/pages/var.xhtml";
    }

    @PostConstruct
    public void initialize() { }

With this code, my @PostConstructis called after my edit method and later it is called again.

I think that I'm using the @PostConstruct in a wrong way (I think MBean needs to be up before any method). But what is the alternative to edit an object in a page different from the search page?

Upvotes: 1

Views: 2042

Answers (1)

Michi
Michi

Reputation: 1595

The problem seems to be that the view scoped managed bean mbean (I think, it is a bit unclear) is used in search.xhtml and var.xhtml.

When you call the action method your are still on view search.xhtml. You get a bean instance bound to view scope for this view and the first call to the @PostConstruct method.

The action method returns the view ID of the second page var.xhtml and JSF navigates to this page. If you use mbean in this page too, you get a new instance of the bean as the view changed. This explains the second call to the @PostConstruct method.

Upvotes: 0

Related Questions