在開發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");
注:原創博客,轉載請注明。
