com.hyf.hotrefresh.adapter.spring.ApplicationContextUtils Maven / Gradle / Ivy
package com.hyf.hotrefresh.adapter.spring;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* 应用上下文工具
*
* @author baB_hyf
* @date 2022/02/09
*/
public class ApplicationContextUtils implements ApplicationContextAware {
private static volatile ApplicationContext ctx;
public static ApplicationContext getApplicationContext() {
if (ctx == null) {
throw new IllegalStateException("ApplicationContext has not been initialized");
}
return ctx;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextUtils.ctx = applicationContext;
}
public static T getBean(Class clazz) {
return getBean(getApplicationContext(), clazz);
}
public static T getBean(ApplicationContext ctx, Class clazz) {
return ctx.getBean(clazz);
}
public static T getBean(String name, Class clazz) {
return getBean(getApplicationContext(), name, clazz);
}
public static T getBean(ApplicationContext ctx, String name, Class clazz) {
return ctx.getBean(name, clazz);
}
public static T getBeanIfExist(Class clazz) {
ApplicationContext ctx = getApplicationContext();
try {
return ctx.getBean(clazz);
} catch (NoSuchBeanDefinitionException ignored) {
return null;
}
}
public static T getBeanIfExist(String name, Class clazz) {
return getBeanIfExist(getApplicationContext(), name, clazz);
}
public static T getBeanIfExist(ApplicationContext ctx, String name, Class clazz) {
if (ctx.containsBean(name)) {
return ctx.getBean(name, clazz);
}
return null;
}
}