您的位置:首页 > 编程语言 > Java开发

JSF结合Spring 引入ViewScope

2015-07-02 15:40 661 查看
  当JSF项目的faceConfig中配置了Spring的配置代码

<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>


  那么JSF里所有的bean都将接受Spring的管理,Spring对实例提供了三种作用域,分别是session、request、application。但JSF的作用域就比较多了,它还有ViewScope、Conversation等等。其中ViewScope用的比较多,翻阅国外站点,找到一个primeFaces论坛提供的可用方法:

1. 首先创建一个Spring的自定义作用域类,代码如下:

  

import java.util.Map;

import javax.faces.context.FacesContext;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

public class ViewScope implements Scope {

@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
//        System.out.println("**************************************************");
//        System.out.println("-------------------- Getting objects For View Scope ----------");
//        System.out.println("**************************************************");
Map<String, Object> viewMap = FacesContext.getCurrentInstance().getViewRoot().getViewMap();
if(viewMap.containsKey(name)){
return viewMap.get(name);
}else{
Object object = objectFactory.getObject();
viewMap.put(name, object);
return object;
}
}

@Override
public String getConversationId() {
return null;
}

@Override
public void registerDestructionCallback(String arg0, Runnable arg1) {

}

@Override
public Object remove(String name) {
//        System.out.println("**************************************************");
//        System.out.println("-------------------- View Scope object Removed ----------");
//        System.out.println("**************************************************");

if (FacesContext.getCurrentInstance().getViewRoot() != null) {
return FacesContext.getCurrentInstance().getViewRoot().getViewMap().remove(name);
} else {
return null;
}
}

@Override
public Object resolveContextualObject(String arg0) {
return null;
}

}


2. 在Spring的配置文件中配置viewScope的作用域。

  

<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="view" value="com.xx.scope.ViewScope" />
</map>
</property>
</bean>


3. 最后是如何引用了,引用比较简单,就是在配置的bean里,加入一个属性 scope="view"即可。ViewScope比RequestScope级别要大,这样对于JSF的里的ajax请求是相当有用的,只要不导航到其他页面,bean就不会离开作用域。

其他:因为ViewScope在进入页面时会新建,在离开页面时会销毁,所以可以利用这个特点做一些bean的初始化及数据释放销毁的操作,借助于@PostConstruct和@PreDestroy注解的方法就可以达到。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: