在項目中,由於想在自定義的JSF Converter中使用Spring Bean,通過搜索和測試,有兩種方式能夠達到目的java
1)使用工具類獲取Spring Bean,這個是最容易想到的
web
//須要在Spring配置文件設置 //<bean id="spring" class="com.ims.webapp.view.util.SpringUtil" /> public class SpringUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext arg0) throws BeansException { SpringUtil.applicationContext = arg0; } public static Object getBean(String name){ return applicationContext.getBean(name); } }
public class ProductInfoConverter implements Converter { protected SupportingDataService supportingDataService; @Override public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String submittedValue) { this.supportingDataService = (SupportingDataService) SpringUtil.getBean("supportingDataService");//這裏經過SpringUtil獲取須要的Spring Bean List<ProductInfo> productInfoList = supportingDataService.getProductInfoList(new ProdSearchCriteria()); return null; } public String getAsString(FacesContext facesContext, UIComponent component, Object value) { if (value == null || value.equals("")) { return ""; } else { return ((ProductInfo)value).getProductCode(); } }
上述方式還有一個要注意的就是:必需要在faces-config.xml裏頭配置這個converter,而後在頁面上直接使用該converter, spring
<converter> <converter-id>productInfoConverter</converter-id> <converter-class>com.ims.webapp.view.converter.ProductInfoConverter</converter-class> </converter>
<p:autoComplete value="#{orderMaintainView.selectedProd}" id="item" completeMethod="#{orderMaintainView.completeProductInfoList}" var="p" itemLabel="#{p.productCode}" itemValue="#{p}" converter="productInfoConverter" forceSelection="true">
2)直接把converter配置成JSF Bean,而後注入Spring Bean,頁面使用時就如通常JSF Bean那樣便可app
@ManagedBean(name="productInfoConverter") @RequestScoped public class ProductInfoConverter implements Converter { @ManagedProperty(value = "#{supportingDataService}") protected SupportingDataService supportingDataService; public SupportingDataService getSupportingDataService() { return supportingDataService; } public void setSupportingDataService(SupportingDataService supportingDataService) { this.supportingDataService = supportingDataService; } @Override public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String submittedValue) { List<ProductInfo> productInfoList = supportingDataService.getProductInfoList(new ProdSearchCriteria()); return null; } public String getAsString(FacesContext facesContext, UIComponent component, Object value) { if (value == null || value.equals("")) { return ""; } else { return ((ProductInfo)value).getProductCode(); } } }
對於第二種方式,須要注意的是:不要在faces-config.xml裏頭配置converter。頁面使用的時候,須要當成變量用,即webapp
#{productInfoConverter}ide
參見 http://stackoverflow.com/questions/10229396/how-to-inject-spring-bean-into-jsf-converter工具