/**
*
* @author guanZheng
* 创建SpringBeanFactoryUtils类
* 实现ApplicationContextAware接口
*
*/
public class SpringBeanFactoryUtils implements ApplicationContextAware {
private static ApplicationContext appCtx;
/**
* 重写setApplicationContext方法
* 此方法可以把ApplicationContext对象inject到当前类中作为一个静态成员变量。
*
* @param applicationContext ApplicationContext 对象.
* @throws BeansException
* @author guanzheng
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringBeanFactoryUtils.appCtx = applicationContext;
}
/**
* 获取ApplicationContext
*
* @return
* @author guanzheng
*/
public static ApplicationContext getApplicationContext() {
return appCtx;
}
/**
* 这是一个便利的方法,帮助我们快速得到一个BEAN
*
* @param beanName bean的名字
* @return 返回一个bean对象
* @author guanzheng
*/
public static Object getBean(String beanName) {
return appCtx.getBean(beanName);
}
}
当我们需要在其他类里面得到Mapper对象时只需要,getBean就行了
如我需要一个ApparatusMapper类,不通过@Autowired注解
if(null==apparatusMapper){
apparatusMapper = SpringBeanFactoryUtils.getApplicationContext().getBean(ApparatusMapper.class);
}