Sunday, August 7, 2011

Spring3 and JSF2 integration using CDI annotations

In this blog i show you how to use @Inject in your JSF managed beans to directly inject the Spring beans instead of instantiating a Spring application context and using the getBean methode from that context and also how Spring will manage your JSF beans ;-)


In order to inject Spring beans into JSF managed beans using @Inject, the following needs to be done:


1)web.xml

 
org.springframework.web.context.ContextLoaderListener


contextConfigLocation

classpath:/applicationContext.xml


org.springframework.web.context.request.RequestContextListener


2) faces-config.xml

 
org.springframework.web.jsf.el.SpringBeanFacesELResolver

3) applicationContext.xml





4) JSF Managed bean

 @ManagedBean(name="blogJSFBean")
@Controller
@ViewScoped
public class MainBean implements Serializable {
private static final long serialVersionUID = -5012655116147710604L;
@Inject
private SpringBean myBlogBean;


To keep it standard i have changed @Managedean to @Named witch is a CDI standard annotation suported by Spring also (as an alternate to @Service and @Controller)

The big problem i have found that the scope view (@ViewScoped) isn't supported by Spring (also Flash scope …) so i have developped the view scope as Spring custom scope following this article: http://cagataycivici.wordpress.com/2010/02/17/port-jsf-2-0s-viewscope-to-spring-3-0/


my bean become:

 @Named("blogJSFBean")
@Scope (value="view")
public class MainBean implements Serializable {
private static final long serialVersionUID = -5012655116147710604L;
@Inject
private SpringBean myBlogBean;


In general the big difference i have found is that Spring and JSF bean from Java EE 6 use a different scoping! Spring do not support standard scope annotation used in JSF and CDI. To get it work i have followed a workaround to import JSF/CDI bean into Spring:

http://matthiaswessendorf.wordpress.com/2010/05/06/using-cdi-scopes-with-spring-3/

Finaly with all this configuration and workarounds, i have been able to inject Spring beans into JSF using @Inject and @Named Java EE standard annotaion and a custom Spring scope to import JSF/CDI scope


No comments:

Post a Comment