中國絕大部分java應用系統都使用spring作爲基礎系統架構的一部分。
對於qlExpress腳本引擎來說,能否調用spring bean的方法?怎麼調用?是一個非常常見的問題。
以下通過案例來說明。有問題請聯繫
微信 371754252
或者郵件 [email protected]
比如說你要執行以下的一段qlExpress腳本,除了orderId等普通變量,
還需要傳入 bizOrderDao,tradeHsfBean,refundHsfBean 等spring bean變量。
order = bizOrderDao.getOrderById(orderId);
if(order.status==2){
return tradeHsfBean.syncOrder(order);
}else{
return refundHsfBean.syncOrder(order);
}
return null;
方案1:手工注入bean
public void test(){
ExpressRunner runner = new ExpressRunner();
DefaultContext<String, Object> context = new DefaultContext<String, Object>();
Context.put(“orderId”,100012L);
Context.put(“bizOrderDao”,getSpringBean("bizOrderDao"));
Context.put(“tradeHsfBean”,getSpringBean("tradeHsfBean"));
Context.put(“refundHsfBean”,getSpringBean("refundHsfBean"));
Object result = runner.execute(text, context, null,true, false);
system.out.println(result);
}
方案2:擴展上下文,自動注入bean
解決方案:把DefaultContext升級爲SpringBeanContext
public class SpringBeanContext extends HashMap<String,Object>
implements IExpressContext<String,Object> {
private ApplicationContext applicationContext;
Public SpringBeanContext(Map<String,Object> aProperties,ApplicationContext applicationContext)
{
super(aProperties);
this.applicationContext = applicationContext;
}
/**
* 根據key從容器裏面獲取對象
*
* @param key
* @return
*/
public Object get(Object key) {
Object object = super.get(key);
try {
if (object == null && this.applicationContext != null
&& this.applicationContext.containsBean((String)key))
{
object = this.applicationContext.getBean((String)key);
}
} catch (Exception e) {
throw new RuntimeException("表達式容器獲取對象失敗", e);
}
return object;
}
/**
* 把key-value放到容器裏面去
*
* @param key
* @param value
*/
public Object put(String key, Object value) {
return super.put(key, value);
}
}
@Service
public SpringBeanRunner implements ApplicationContextAware
{
private ApplicationContext applicationContext;
private ExpressRunner runner;
@override
public void setApplicationContext(ApplicationContext context) {
this.applicationContext = context;
runner = new ExpressRunner();
}
public Object executeExpress(String text,Map<String,Object> context)
{
IExpressContext<String,Object> expressContext = new SpringBeanContext(context,this.applicationContext);
try{
return runner.execute(text, expressContext, null, true, false);
}catch(Exception e){
logger.error("qlExpress運行出錯!",e);
}
return null;
}
}
至此,通過對runner的簡單封裝,你現在只要直接使用這樣的代碼就可以輕鬆完成你對bean的調用了。
@Resource
private SpringBeanRunner runner;
public void test(){
Map<String, Object> context = new HashMap<String, Object>();
Context.put(“orderId”,100012L);
Object result = runner.executeExpress(text, context);
system.out.println(result);
}
附錄:你可能會遇到的坑
1、bean取出來爲空
檢查下applicationContext裏面,對應的com.taobao.XXXX.BizOrderDAO名稱是否真的是“bizOrderDAO”
(1)spring註解問題
spring的默認註解使用byType,在applicationContext不是名稱,請指定name或者使用ByName
@Service("tradeHsfBean")
public class TradeHsfBean{
}
(2)ApplicationContext注入失敗
SpringBeanRunner沒有調用到setApplicationContext(ApplicationContext context) 方法,請調試一下。