標籤:代碼 param function exce stl str war static ring
在開發Dubbo的過程中,多次讀取同一設定檔載入上下文是錯誤的方法,對於已經載入到Spring容器中的context對象,其實是可以通過實現介面來擷取的。
首先,實現ApplicationContextAware介面,自訂的實作類別SpringContextUtil。
SpringContextUtil.java
package com.mohrss.service;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;/* * Class: SpringContextUtil * Function:用於獲得當前Spring上下文環境的工具類 */public class SpringContextUtil implements ApplicationContextAware {// Spring應用上下文環境 private static ApplicationContext context; /** * 實現ApplicationContextAware介面的回調方法。設定上下文環境 * * @param applicationContext */ public void setApplicationContext(ApplicationContext applicationContext) { SpringContextUtil.context = applicationContext; } /** * @return ApplicationContext */ public static ApplicationContext getApplicationContext() { return context; } public static Object getBean(String name) throws BeansException { return context.getBean(name); } }
實現這個工具類後,需要在設定檔中進行配置。
<bean id="springContextUtil" class="com.mohrss.plugin.SpringContextUtil" />
之後即可在代碼中進行調用,如:
LogService ls = (LogService)SpringContextUtil.getApplicationContext().getBean("testLogService");
註:原創部落格,轉載請註明。
[Spring開發]擷取內容物件