Search code examples
jsfdependency-injectionpostconstruct

Will Bean get created if @PostConstruct fails


I've been trying to solve an issue where my managedBean is sometimes null (I get the target unreachable error message saying that the bean is null) and this intermittent issue usually occurs if I tinker in the @PostConstruct method.

While booting up the application I really don't see any errors, but as soon as I try to interact with the bean via XHTML, BOOM! Bean is null. I read through the @PostConstruct documentation and it says that if an exception should occur, "the bean is not put into service" does this mean that JSF won't create/handle the bean. Can a failing @postConstruct be the cause of my null bean (based on what I've mentioned)? If say the @PostConstruct where failing for some reason, why am I not seeing the exception in the server log (is it supposed to fail gracefully)?

Sorry, this is theoretical but it's the only thing that makes sense to me, and showing code really won't help since it's so difficult to root cause.

Another question - How can I catch/debug any issues in the @PostConstruct?

Thanks for your time, sorry If I didn't follow some Q&A Stackoverflow guidelines.


Solution

  • If you have JSF @ManagedBean, the instantiation of the bean is lazy by default. That means that bean will only be created when the request will come. That's why you don't see the error while booting your application. The managedBean annotation has property named eager, which you can set to true, but it will work when application starts only for applicationScope beans, as it said in the documentation.

    The creation lifecycle typically follow this steps: bean creation by invoking default constructor -> wiring all needed managed properties and environment -> calling @PostConstruct method -> if all of that is successfull that's when the bean is ready to serve the request.

    Usually all containers that manages beans are telling about problem occured when one of the step is not worked properly. In order to debug that you can just try to catch any exception in postConstruct method. Another option is to enable development stage on you JSF application, which is done via setting the property in web.xml file for facesServlet like this:

    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
    

    This will give you more debug information in case of errors. You should read your JSF provider documentation about information provided while getting errors as it may vary or consult with JSF specification itself.

    But as far as you getting nothing in logs I assume that there are some errors in configuration or maybe the page itself. In order to determine that you should provide more information about you exact problem.