package com.cggol.commons;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* 通过此类获取Spring容器中,注册类的对象
* 使用此类时,请在Spring的配置文件中,配置该类
*
*/
public class ApplicationContextHelper implements ApplicationContextAware
{
//以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext
private static ApplicationContext APPLICATION_COUNT;
/** * 取得存储在静态变量中的ApplicationContext.*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
{
ApplicationContextHelper.APPLICATION_COUNT = applicationContext;
}
public static <T> T getBean(String beanName, Class<T> clazz)
{
return APPLICATION_COUNT .getBean(beanName,clazz);
}
/** * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.*/
public static Object getBean(String beanName)
{
return APPLICATION_COUNT .getBean(beanName);
}
}
//用到该类时,在applicationContext.xml中引用此类
<!-- 将Spring容器对象注入此类 -->
<bean class=“引入该类路径”/>