解決Spring在某些條件下無法自動注入的問題
阿新 • • 發佈:2019-01-03
靜態工具類:
package org.digdata.swustoj.util;
import lombok.Getter;
import lombok.NonNull;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* Created by hongfei.whf on 2016/10/31.
*/
public class ContextUtil implements ApplicationContextAware {
@Getter
private static volatile ApplicationContext context = null;
/**
* 載入Spring配置檔案時,如果Spring配置檔案中所定義的Bean類實現了ApplicationContextAware 介面,那麼在載入Spring配置檔案時,會自動呼叫ApplicationContextAware 介面中的
* public void setApplicationContext(ApplicationContext context) throws BeansException
* & 方法,獲得ApplicationContext物件
*
* @param applicationContext
* @throws BeansException
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
/**
* 獲取bean
*
* @param clazz
* @param beanName
* @param <T>
* @return
*/
public static <T> T getBean(@NonNull Class<T> clazz, @NonNull String beanName) {
return (T) context.getBean(beanName);
}
}
在xml中定義bean
<!--手動bean定義-->
<bean class="org.digdata.swustoj.util.ContextUtil"/>
使用示例
/**
* 判題佇列
*/
private DefaultJudgeQueue defaultJudgeQueue = ContextUtil.getBean(DefaultJudgeQueue.class, "defaultJudgeQueue");