线程中取Spring管理的Bean的工具类
使用Spring时,手动开启多线程时需要注入Spring管理的对象,如果使用@Resource
注解,会报空指针异常。
下面给出获取Spring管理的对象的工具类:
import java.util.Locale;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* 线程中取Spring管理的Bean的工具类
* @author WJY
*/
@Repository
public class SpringApplicationContextHolder implements ApplicationContextAware{
private static ApplicationContext context = null;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringApplicationContextHolder.context = applicationContext;
}
@SuppressWarnings("unchecked")
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());
}
}
applicationContext.xml配置如下:
<!--spring bean 工具类-->
<bean id="springContextUtil" class="com.wjyup.util.SpringApplicationContextHolder"/>
使用方法:SpringApplicationContextHolder.getBean("name");