I was wondering about how the integration of JSF and the community’s new hot IOC Framework Guice can be done and later figured out a way. The example I’ve created is simple, there’s a JSF page used for creating an Account entity, a service class AccountService that implements IAccountService, and a JSF managed bean serving as the backing bean of the JSF page. Simply the JSF bean has a dependency to IAccountService and the injection is done via Guice.
Account
|
IAccountService
|
AccountService
|
createAccount form
| <%@ taglib uri=”http://java.sun.com/jsf/html” prefix=”h” %> <%@ taglib uri=”http://java.sun.com/jsf/core” prefix=”f” %> <html> <head> <title>Create an Account</title> </head> <body> <f:view> <h:form> <h:panelGrid columns=”2″> <h:outputLabel value=”Name” for=”txt_name”></h:outputLabel> <h:inputText id=”txt_name” value=”#{createAccount.account.name}” /> <h:outputLabel value=”Password” for=”txt_password”></h:outputLabel> <h:inputSecret id=”txt_password” value=”#{createAccount.account.password}” /> </h:panelGrid> <h:commandButton action=”#{createAccount.save}” value=”Save” /> </h:form> </f:view> </body> </html> |
CreateAccount
|
BaseBackingBean
|
Listener (To be defined in web.xml)
|
GuiceJSFModule
|
The idea here is, the backing JSF bean is created by JSF IOC but it’s dependencies like IAccountService is injected by Guice. At startup, a listener creates and sets a Guice Injector to application scope(I get the listener idea from this blog). This part can be refactored so that the module lists are not hardcoded and retrieved from a context param instead. Anyway, when a JSF bean is created, the method annotated with @PostConstruct gets the injector and calls the injection procedure. This @PostConstruct is called after the bean is created but before being put into it’s scope.
The example is a kickstart for an app that uses JSF and Guice, frankly I don’t think Guice fits the JSF model well, the @PostConstruct is a JSF 1.2 feature and it’ll be problematic to do a similar thing with JSF 1.1. I’m not a spring fan but using spring 2.0 with JSF is very easy and effective compared to Guice since it’s also possible to define the JSF beans in Spring Context with different scopes, apply AOP on them, add BeanPostProcessor to add custom lifecycle logics and etc.