JSF - Can @PostConstruct block setter method by us

2019-02-27 10:02发布

问题:

I think the question is clear by the title. This is my actual bean :

@ManagedBean(name="selector")
@RequestScoped
public class Selector {
    private String profilePage;

    @PostConstruct
    public void init() {
        System.out.println("I'm PostConstruct");
        if(profilePage==null || profilePage.trim().isEmpty()) {
            this.profilePage="main";
        }
    }

    public String getProfilePage() { 
        return profilePage;
    }

    public void setProfilePage(String profilePage) { 
        this.profilePage=profilePage;
        System.out.println("I'm setProfilePage");
    }
}

And i change his value (profilePage) by using ajax call :

<h:commandButton value="Some Action">
    <f:setPropertyActionListener target="#{selector.profilePage}" value="some" />
    <f:ajax event="action" render=":profileContent"/>
</h:commandButton>

I notice that my output on server is not ever a sequence of I'm PostConstruct followed by I'm setProfilePage. Sometimes I'm setProfilePage is totally absent.

I read that Methods marked with the @PostConstruct annotation will be invoked after the bean has been created, any resources have been injected, and any managed properties set, but before the bean is actually pushed into scope.

I would like to know if @PostConstruct can make some conflicts with setter method.

Cheers

回答1:

Sometimes I'm setProfilePage is totally absent.

That can happen when the UICommand component is not rendered in the component tree during apply request values phase and/or update model values phase. I.e. the rendered attribute of it or one of its parents has evaluated false at that point.

The presence of @PostConstruct should not have any influence.



回答2:

As BalusC indicates, having a rendered attribute set to false at a postback is quite often a cause for action methods not being executed. This typically happens when such attribute defaults to false and is only later in the JSF life-cycle (i.e. after apply request values) set to true.

Defaulting to true (if possible) or remembering the value of this attribute by using the view scope or something like the Tomahawk saveState tag often gets you around this problem.

In addition I would like to mention that next to PostConstruct, AJAX also should have nothing to do with this problem.