io.geewit.web.utils.SpringContextUtil Maven / Gradle / Ivy
package io.geewit.web.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import java.util.Map;
/**
* 以静态变量保存Spring ApplicationContext.
* @author geewit
*/
@Configuration
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
public static T getBean(String name, Class clazz) throws BeansException {
return applicationContext.getBean(name, clazz);
}
public static T getBean(Class clazz) {
return getBean(clazz, applicationContext);
}
public static T getBean(Class clazz, ApplicationContext ctx) {
Map map = ctx.getBeansOfType(clazz);
if (map.size() == 0) {
return null;
} else if (map.size() > 1) {
new IllegalArgumentException("bean is not unique.").printStackTrace();
}
return map.values().iterator().next();
}
}