ApplicationContextHolder通過這個例項來獲取一個已經注入了的bean.
阿新 • • 發佈:2019-02-15
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* 寫一個工具類實現ApplicationContextAware介面,並將這個加入到spring的容器
* ApplicationContextHolderGm.getBean("xxxDao");
* 通過這個例項來獲取一個已經注入了的bean.
* @author jiayi
*
*/
public class ApplicationContextHolderGm implements ApplicationContextAware,DisposableBean{
private static Logger log = LoggerFactory.getLogger(ApplicationContextHolderGm.class);
private static ApplicationContext applicationContext;
@SuppressWarnings("all")
public void setApplicationContext(ApplicationContext context) throws BeansException {
if (this.applicationContext != null) {
throw new IllegalStateException("ApplicationContextHolderGm already holded 'applicationContext'.");
}
this.applicationContext = context;
log.info("holded applicationContext,顯示名稱:" + applicationContext.getDisplayName());
}
/**獲取applicationContext物件*/
public static ApplicationContext getApplicationContext() {
if (applicationContext == null) {
throw new IllegalStateException(
"'applicationContext' property is null,ApplicationContextHolder not yet init.");
}
return applicationContext;
}
/**
* 根據bean的id來查詢物件
* @param id
* @return
*/
public static Object getBeanById(String id){
checkApplicationContext();
return applicationContext.getBean(id);
}
/**
* 通過名稱獲取bean
* @param name
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name){
checkApplicationContext();
Object object = applicationContext.getBean(name);
return (T)object;
}
/**
* 根據bean的class來查詢物件
* @param c
* @return
*/
@SuppressWarnings("all")
public static <T> T getBeanByClass(Class<T> c){
checkApplicationContext();
return (T)applicationContext.getBean(c);
}
/**
* 從靜態變數ApplicationContext中取得Bean, 自動轉型為所賦值物件的型別.
* 如果有多個Bean符合Class, 取出第一個.
* @param cluss
* @return
*/
public static <T> T getBean(Class<T> cluss){
checkApplicationContext();
return (T)applicationContext.getBean(cluss);
}
/**
* 名稱和所需的型別獲取bean
* @param name
* @param cluss
* @return
*/
public static <T> T getBean(String name,Class<T> cluss){
checkApplicationContext();
return (T)applicationContext.getBean(name,cluss);
}
public static <T> Map<String,T> getBeansOfType(Class<T> type) throws BeansException{
checkApplicationContext();
return applicationContext.getBeansOfType(type);
}
/**
* 檢查ApplicationContext不為空.
*/
private static void checkApplicationContext() {
if (applicationContext == null) {
throw new IllegalStateException("applicaitonContext未注入,請在applicationContext.xml中定義ApplicationContextHolderGm");
}
}
@Override
public void destroy() throws Exception {
checkApplicationContext();
}
/**
* 清除applicationContext靜態變數
*/
public static void cleanApplicationContext(){
applicationContext = null;
}
}