package cn.huge.base.common.context;
|
|
import org.springframework.context.ApplicationContext;
|
import org.springframework.context.ApplicationContextAware;
|
import org.springframework.stereotype.Service;
|
|
/**
|
* @title: 获取非spring容器管理的bean
|
* @description: 获取非spring容器管理的bean
|
* @company: hugeinfo
|
* @author: liyj
|
* @time: 2021-11-05 16:51:48
|
* @version: 1.0.0
|
*/
|
@Service
|
public class ApplicationContextHolder implements ApplicationContextAware {
|
private static ApplicationContext context;
|
|
/**
|
* 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
|
*/
|
public void setApplicationContext(ApplicationContext applicationContext) {
|
context = applicationContext;
|
}
|
|
/**
|
* 取得存储在静态变量中的ApplicationContext.
|
* @return
|
*/
|
public static ApplicationContext getContext() {
|
return context;
|
}
|
|
/**
|
* 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
|
* @param name
|
* @param <T>
|
* @return
|
*/
|
public static <T> T getBean(String name) {
|
checkContext();
|
return (T)context.getBean(name);
|
}
|
|
/**
|
* 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
|
* 如果有多个Bean符合Class, 取出第一个.
|
* @param clazz
|
* @param <T>
|
* @return
|
*/
|
public static <T> T getBean(Class<T> clazz) {
|
checkContext();
|
return (T)context.getBeansOfType(clazz);
|
}
|
|
public static void cleanContext() {
|
context = null;
|
}
|
|
private static void checkContext() {
|
if (context == null)
|
throw new IllegalStateException("上下文未注入, 请在spring容器中定义ApplicationContextHolder");
|
}
|
}
|
/**
|
* -------------------_ooOoo_-------------------
|
* ------------------o8888888o------------------
|
* ------------------88" . "88------------------
|
* ------------------(| -_- |)------------------
|
* ------------------O\ = /O------------------
|
* ---------------____/`---'\____---------------
|
* -------------.' \\| |// `.-------------
|
* ------------/ \\||| : |||// \------------
|
* -----------/ _||||| -:- |||||- \-----------
|
* -----------| | \\\ - /// | |-----------
|
* -----------| \_| ''\---/'' | |-----------
|
* -----------\ .-\__ `-` ___/-. /-----------
|
* ---------___`. .' /--.--\ `. . __----------
|
* ------."" '< `.___\_<|>_/___.' >'"".-------
|
* -----| | : `- \`.;`\ _ /`;.`/ - ` : | |-----
|
* -----\ \ `-. \_ __\ /__ _/ .-` / /-----
|
* ======`-.____`-.___\_____/___.-`____.-'======
|
* -------------------`=---='
|
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
* ---------佛祖保佑---hugeinfo---永无BUG----------
|
*/
|