io.geewit.web.utils.SpringContextUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of gw-web-utils-core Show documentation
Show all versions of gw-web-utils-core Show documentation
A Java Utils Libraray By Geewit
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 getBean(name, clazz, applicationContext);
}
public static T getBean(Class clazz) {
return getBean(null, clazz, applicationContext);
}
public static T getBean(String name, Class clazz, ApplicationContext ctx) {
Map map = ctx.getBeansOfType(clazz);
if (map.isEmpty()) {
return null;
}
if (name != null) {
return map.get(name);
}
return map.values().iterator().next();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy