package com.study.demo.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
public class ApplicationContextUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationContextUtil.class);
private static ApplicationContext applicationContext;
private ApplicationContextUtil() {
}
static void setApplicationContext(ApplicationContext applicationContext) {
ApplicationContextUtil.applicationContext = applicationContext;
}
private static boolean checkApplicationContext() {
if (applicationContext == null) {
LOGGER.info("未獲取ApplicationContext");
}
return applicationContext != null;
}
public static Object getBean(String beanName) {
Object result = null;
if (checkApplicationContext()) {
try {
result = applicationContext.getBean(beanName);
} catch (Exception e) {
LOGGER.error("獲取Bean異常 e:{}", e);
}
}
return result;
}
public static <T> T getBean(String beanName, Class<T> className) {
T result = null;
if (checkApplicationContext()) {
try {
result = applicationContext.getBean(beanName, className);
} catch (Exception e) {
LOGGER.error("獲取Bean異常 e:{}", e);
}
}
return result;
}
}
ApplicationContext的使用
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.