Search code examples
springjsfannotationsjsf-2postconstruct

@PostConstruct doesn't work if are declared only action method


guys i'm using jsf 2.0 with spring. I have annotated a method in a managed bean with @PostConstruc, but if in the bean there aren't field connected to the jsf page the @PostConstruct method isn't called even if in the jsf page there is an action method connected to the Bean. Thank you in advance.

Added code for explaination:

this si my BackingManagedBean

@ManagedBean(name="utenteBean")
@ViewScoped
public class UtenteBean extends SupportBean implements Serializable

While this is my ControllerManagedBean

@ManagedBean(name="gestisciUtentiController")
@ViewScoped
public class GestisciUtentiController extends MessageSupportBean implements Serializable {

@ManagedProperty(value="#{utenteBean}")
private UtenteBean utenteBean;
public void setUtenteBean(UtenteBean utenteBean) {
    this.utenteBean = utenteBean;
}

    @PostConstruct
    public void loadBean()
    {
        try
        {
            utenteBean.setUtentis(getFacadeFactory().getUtenteFacade().readAllOrdered(Utente.class, "username"));
        }
        catch (ApplicationException e)
        {
            setExceptionMessage(e.getLocalizedMessage(), e.getLocalizedMessageDetail());
        }
    }

Solution

  • http://blog.icefaces.org/blojsom/blog/default/2009/04/23/Making-distinctions-between-different-kinds-of-JSF-managed-beans/ i'm trying to use this approch. You think that that approch isn't correct? –

    I'm not sure. That article mentions that the model is typically to be placed in the session scope. This is actually a poor approach. Injecting a session scoped bean in a request scoped bean makes sense if the session scoped one is for example the logged-in user and the request scoped one is bound to the form.

    In your case you should just make the model bean a property of the controller bean and use #{gestisciUtentiController.utenteBean.someProperty} instead of #{utenteBean.someProperty}.

    I've some "JSF design" questions before, you may find them useful as well: