在开发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");
注:原创博客,转载请注明。