import javax.faces.FactoryFinder;
import javax.faces.application.Application;
import javax.faces.application.ApplicationFactory;
import javax.faces.context.FacesContext;
import javax.faces.el.ValueBinding;
import javax.servlet.ServletContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public final class SpringFacesUtil {
public SpringFacesUtil() {
}
/**
* 从Spring中查找bean.
* @param beanName String
* @return Object
*/
public static Object findSpringBeanByName(String beanName) {
ServletContext context = (ServletContext) FacesContext
.getCurrentInstance().getExternalContext().getContext();
ApplicationContext appctx = WebApplicationContextUtils
.getRequiredWebApplicationContext(context);
return appctx.getBean(beanName);
}
/**
* 由spring的xml配置文件位置和bean的名字取得bean
* @param xmlPath spring配置文件位置
* @param beanName 要取得bean的名字
* @return
*/
public static Object findSpringBeanByPath(String xmlPath,String beanName){
ApplicationContext ctx =new FileSystemXmlApplicationContext(xmlPath);
return ctx.getBean(beanName);
}
/**
* 从JSF中查找bean.
* @param beanname String
* @return Object
*/
@SuppressWarnings("deprecation")
public static Object lookupJsfBean(String beanname) {
Object obj = getValueBinding(getJsfEl(beanname)).getValue(
FacesContext.getCurrentInstance());
return obj;
}
@SuppressWarnings("deprecation")
private static ValueBinding getValueBinding(String el) {
return getApplication().createValueBinding(el);
}
private static Application getApplication() {
ApplicationFactory appFactory = (ApplicationFactory) FactoryFinder
.getFactory(FactoryFinder.APPLICATION_FACTORY);
return appFactory.getApplication();
}
private static String getJsfEl(String value) {
return "#{" + value + "}";
}
}