两种方式实例化容器并获取bean

package com.bitbao.cm.cron;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;


public class AppContextStandAlone {
	
	private static ApplicationContext ac;
	
	public static<T> T getBean(String beanName, Class<T> cls) {
		if(ac == null){
			initAc();
		}
		return ac.getBean(beanName, cls);
	}
	
	public static void initAc(){
		/* 使用绝对路径
		String filePath = CMConfig.getProperty("AppStandAloneConfigPath");
		System.out.println(filePath);
		ac = new FileSystemXmlApplicationContext("file:" + filePath);
		*/
		// 使用classpath
		//URL url = AppContextStandAlone.class.getResource("classpath:" + "/configure/app/root.xml");/bitbao_web/WebContent/WEB-INF/configure/app/root.xml
		ac = new FileSystemXmlApplicationContext("classpath:" + "/configure/app/root.xml");
	}
}
package com.bitbao.cm.common.context;

import javax.servlet.ServletRequest;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.support.RequestContextUtils;

public class AppContext {

	private static final ThreadLocal<WebApplicationContext> wac = new ThreadLocal<WebApplicationContext>();

	public static void setWAC(WebApplicationContext wac) {
		if (AppContext.wac.get() == null) {
			AppContext.wac.set(wac);
		}
	}
	
	public static void setWAC(ServletRequest request){
		if (AppContext.wac.get() == null) {
			AppContext.wac.set(RequestContextUtils.getWebApplicationContext(request));
		}
	}
	
	public static WebApplicationContext getWac(){
		return AppContext.wac.get();
	}

	public static<T> T getBean(String beanName, Class<T> cls) {
		return AppContext.wac.get().getBean(beanName, cls);
	}
}
 

相关推荐