日期:2014-05-16  浏览次数:20306 次

JSF和Spring的集成之二
使用框架
1 介绍
这个框架是Spring相关项目,提供一个包de.mindmatters.faces.spring,这个包包含JSF和Spring框架综合集成的粘合代码,这些代码以独立于一个实现的方式完成,这样它能和任何JSF实现一起使用.
本包的提供的代码主要目的是尽可能透明的集成两个框架,主要特征:
l         JSF/JSP开发者应该能访问Spring管理的Beans,就好象它们是由JSF管理的.
l         JSF可管理beans应能集成入Spring.
l         RequestHandledEvent事件也应该能被发布到Spring.
2 JSF配置集成
本包构造了一个基于faces配置文件(e.g. /WEB-INF/faces-config.xml)的WebApplicationContext类, 让它成为遵循"spring-beans" DTD配置文件(e.g. defined in /WEB-INF/applicationContext.xml)来配置的ApplicationContext的孩子,这样依从"faces-config" DTD的WebApplicationContext就是全特征的,即自动拥有如下功能:
l         JSF可管理beans实现了Spring的*Aware interfaces:
ApplicationContextAware
BeanFactoryAware
BeanNameAware
ResourceLoaderAware
ServletContextAware
l         JSF可管理beans实现Spring的lifecycle interfaces:
InitializingBean
DisposableBean
l         实现Spring的FactoryBean interface
l         实现Spring的ApplicationListener interface
l         发布ApplicationEvent事件.
l         从资源中读取消息.
等等,更多可看Spring.
3 访问方式
1) 从JSF中程序化的访问Spring管理的beans.
因为在FacesWebApplicationContext和ApplicationContext之间有层次关系,所以你的JSF可管理支持beans能容易的实现ApplicationContextAware接口,并能通过getBean方法访问它而不管它是否定义在FacesWebApplicationContext中还是定义在父ApplicationContext类对象中.
2) 通过JSF EL从JSF中访问Spring管理的beans.
能够使用JSF EL访问beans无论你引用的bean由JSF管理还是由Spring管理.两个bean上下文在存取时间合并.
a) 直接访问:
如果一个带有请求名字的bean只存在于Spring上下文内的话,这个bean被使用,bean的singleton属性设置被完全保持.
b) 区域化访问(scoped access):
如果你要从JSF定义bean的作用域的能力上得益还想让那个bean由Spring管理,那么就要在两个上下文中定义,只是对于JSF上下文中的定义的类类型要使用de.mindmatters.faces.spring.SpringBeanFactory类,你还应该设置那个bean的singleton属性到false,因这能覆盖你的作用域设置.在你使用JSF EL访问bean时,你总能获得一个遵从你在JSF上下文中定义的作用域设置的由Spring管理的bean的实例.
三 用法
通常,就象设置任何其它JSF web应用一样设置你的web应用,下面的样例配置展示怎样使能上面提到的特征。
在web.xml配置中必须加入下列配置条目,同时注意把该库的jsf-spring.jar放在适当的位置.
<web-app>
    .........
    <!--
        过滤器用于向Spring发布RequestHandledEvent,它应该影射到和FacesServlet url相同的模式.
    -->  
    <filter>
        <filter-name>RequestHandled</filter-name>
        <filter-class>de.mindmatters.faces.spring.support.RequestHandledFilter</filter-class>
    </filter>
     
    <filter-mapping>
        <filter-name>RequestHandled</filter-name>
        <url-pattern>*.faces</url-pattern>
    </filter-mapping>
    <!--
    这个侦听器用于装入Spring beans的父应用上下文.
    -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    .........
</web-app>
下面的一些说明,都可以通过下载这个Spring相关项目得到,列在这里只为演示上面的说明的功能.
WEB-INF/faces-config.xml
<!-- 一个纯JSF管理的bean -->
<managed-bean>
    <managed-bean-name>jsfBean</managed-bean-name>
    <managed-bean-class>example.NameBean</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
    <managed-property