import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Spring工具類(lèi),提供取得Spring配置文件中定義的Bean的方法<br>用于單元測(cè)試
* @author http://hi.baidu.com/rascal_hu
*
*/
public class SpringUtil {
/** 唯一實(shí)例 */
private static SpringUtil INSTALL = null;
/**Spring工廠接口*/
private BeanFactory beanFactory = null;
/** Spring配置文件 */
private static final String SPRING_CFG = "file:WebRoot/WEB-INF/spring-*.xml";
/** 私有構(gòu)造器 */
private SpringUtil() {
}
/**
* 取得類(lèi)的唯一實(shí)例
* @return
*/
public synchronized static SpringUtil getInstance() {
if (INSTALL == null) {
INSTALL = new SpringUtil();
}
return INSTALL;
}
/**
* 取得BeanFactory
*/
private synchronized BeanFactory getBeanFactory() {
if (this.beanFactory == null) {
this.beanFactory = new ClassPathXmlApplicationContext(SPRING_CFG);
}
return this.beanFactory;
}
/**
* 通過(guò)在Spring配置文件中定義的bean名稱(chēng),從IOC容器中取得實(shí)例
*
* @param beanName
* bean名稱(chēng)
* @return bean名稱(chēng)對(duì)應(yīng)實(shí)例Object,使用時(shí)需要強(qiáng)制類(lèi)型轉(zhuǎn)換
*/
public Object getBean(String beanName) throws NullPointerException {
if (beanName == null) {
throw new java.lang.NullPointerException("beanName不能為空!");
}
return this.getBeanFactory().getBean(beanName);
}
public static void main(String[] args) {
// TODO
// 測(cè)試代碼
}
}
聯(lián)系客服