com.github.xiaoyuge5201.prop.SpringContextUtil Maven / Gradle / Ivy
package com.github.xiaoyuge5201.prop;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import java.util.Map;
/**
* @author xiaoyuge
*/
public class SpringContextUtil implements ApplicationContextAware {
/**
*
*/
private static ApplicationContext applicationContext;
/**
* 实现ApplicationContextAware接口的回调方法,设置上下文环境
*
* @param applicationContext 上下文
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextUtil.applicationContext = applicationContext;
}
/**
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 获取对象
* 这里重写了bean方法,起主要作用
* @param name
* @return Object 一个以所给名字注册的bean的实例
* @throws BeansException
*/
public static Object getBean(String name) throws BeansException {
return applicationContext.getBean(name);
}
/**
* 根据类型获取bean
*
* @param clazz bean类型
* @return 指定类型的bean
*/
public static T getBean(Class clazz) {
T t = null;
Map map = applicationContext.getBeansOfType(clazz);
for (Map.Entry entry : map.entrySet()) {
t = entry.getValue();
}
return t;
}
/**
* 是否包含bean
*
* @param beanName bean名字
* @return boolean,是否包含指定名字的bean
*/
public static boolean containsBean(String beanName) {
return applicationContext.containsBean(beanName);
}
/**
* 是否是单例
*
* @param beanName bean名字
* @return boolean, 是否是单例
*/
public static boolean isSingleton(String beanName) {
return applicationContext.isSingleton(beanName);
}
/**
* bean的类型
*
* @param beanName bean名字
* @return bean的类型
*/
public static Class getType(String beanName) {
return applicationContext.getType(beanName);
}
}