在项目中,因为想在自定义的JSF Converter中使用Spring Bean,经过搜索和测试,有两种方式可以达到目的
1)使用工具类获取Spring Bean,这个是最容易想到的
//需要在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,
<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那样即可
@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。页面使用的时候,需要当成变量用,即
#{productInfoConverter}
参见 http://stackoverflow.com/questions/10229396/how-to-inject-spring-bean-into-jsf-converter