本文来自:http://www.w2bc.com/article/234085
一、写好获取bean的工具类
import java.util.Locale;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* 类名: SpringContextUtil
* 描述: 获取bean的工具类,可用于在线程里面获取bean
*/
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext context = null;
/* (non Javadoc)
* @Title: setApplicationContext
* @Description: spring获取bean工具类
* @param applicationContext
* @throws BeansException
* @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.context = applicationContext;
}
public static <T> T getBean(String beanName){
return (T) context.getBean(beanName);
}
public static String getMessage(String key){
return context.getMessage(key, null, Locale.getDefault());
}
}
二、在spring的配置文件里面注册这个工具类,我的是在spring-mybatis.xml,即spring和mybatis的整合配置文件中。
<!-- 注册Spring工具类 -->
<bean id="springContextUtil" class="com.kgzt.idcqzt.pub.SpringContextUtil"></bean>
三、在线程里面获取bean
/*
* 在线程中是不能直接从容器中获取bean的,
* 需要另写一个工具类来获取
* */
KeepAliveService keepAliveService = SpringContextUtil.getBean("keepAliveService");