Monday, May 2, 2011

What to do if @PostConstruct is not called for JSF managed beans?

I have read and faced self the problem that methods annotated with @PostConstruct / @PreDestroy get never called. Even in JEE 6 compliant servers (weird). This problem had e.g. Tomcat in early 6.x releases, Jetty 6.1.x, etc. Jetty 6.1.x maven plugin can not be used than during development.

There is a simple solution when using Mojarra JSF. Well, if you use Spring framework, you probably don't have this problem. This post provides a solution for JSF projects without Spring (because it doesn't make sense to use Spring in small, lightweight projects). Since Mojarra 1.2 there is a context parameter for web.xml com.sun.faces.injectionProvider. This parameter specifies a class that implements the InjectionProvider SPI. This implementation represents a hook the JSF implementation will use to provide resource injection support. If no provider, shipped with application server, was found and @PostConstruct / @PreDestroy are not called, we can set the value for this context parameter to com.sun.faces.vendor.WebContainerInjectionProvider as follows
<context-param>
    <param-name>com.sun.faces.injectionProvider</param-name>
    <param-value>
        com.sun.faces.vendor.WebContainerInjectionProvider
    </param-value>
</context-param>
Annotations will be parsed and annotated methods invoked now and you will see a message during application startup.
...
02.05.2011 16:04:13 com.sun.faces.spi.InjectionProviderFactory createInstance
INFO: JSF1048: PostConstruct/PreDestroy-Annotationen available. ...
...
It's also possible to use the JBoss implementaion org.jboss.web.jsf.integration.injection.JBossInjectionProvider. I have never tested it, but I think it would be a proper alternative.
<context-param>
    <param-name>com.sun.faces.injectionProvider</param-name>
    <param-value>
        org.jboss.web.jsf.integration.injection.JBossInjectionProvider
    </param-value>
</context-param>
JBoss 5 and above uses it automatically, so that no needs exist for the mentioned parameter.

5 comments:

  1. Thank you. this information really help me.

    ReplyDelete
  2. How can we implement this is tomcat 6?

    ReplyDelete
  3. You are Big. I was looking solution from 2 days. Jboss As 7.1.1. not work with Primefaces

    ReplyDelete
  4. I have the same problem....(JSF with Spring) on JBOSS 5.1 with RichFaces....How to reslove

    ReplyDelete
  5. Thanks Oleg it's worked for me... :)

    ReplyDelete

Note: Only a member of this blog may post a comment.