两种方式实例化容器并获取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); } }
相关推荐
杜鲁门 2020-11-05
与卿画眉共浮生 2020-10-14
lukezhong 2020-10-14
tangxiong0 2020-09-03
YangHuiLiang 2020-08-06
Sweetdream 2020-08-03
编程点滴 2020-07-29
smalllove 2020-07-27
iconhot 2020-07-05
XGQ 2020-07-04
MicroBoy 2020-07-04
itjavashuai 2020-07-04
zmysna 2020-07-04
willluckysmile 2020-06-29
CoderBoy 2020-06-28
爱莲说 2020-06-26
itjavashuai 2020-06-25
HappyHeng 2020-06-21
smalllove 2020-06-14