applicationContext获取

本文详细探讨了在Spring Web应用中如何通过不同方式获取WebApplicationContext,包括使用Session、ServletContext监听器、当前线程上下文以及XML配置文件加载上下文的方法。同时介绍了在独立应用程序中使用ClassPathXmlApplicationContext和FileSystemXmlApplicationContext实例化上下文的实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

1

//自己:
request.getSession().getServletContext().getAttribute("org.springframework.web.context.WebApplicationContext.ROOT")
//官方:
public class MyInitializer implements ServletContextListener {

	public void contextDestroyed(ServletContextEvent sce) {
		// TODO Auto-generated method stub
		
	}

	public void contextInitialized(ServletContextEvent sce) {
		ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());  //sce---ServletContextEvent
		
	}

	
}

 

2

在web中如:servlet

WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();

//source
public static WebApplicationContext getCurrentWebApplicationContext() {
		
	return (WebApplicationContext) currentContextPerThread.get(Thread.currentThread().getContextClassLoader());
	
}

 

 

3

public class MyApplicationHelper implements ApplicationContextAware {

	
		
	private ApplicationContext applicationContext;	
	public void setApplicationContext(ApplicationContext applicationContext)
 throws BeansException {
			
		this.applicationContext = applicationContext;
	
	}

	
	
	public  ApplicationContext getApplicationContext(){
		return this.applicationContext;
	
	}

}

 

 

 

 

main独立应用程序中

 

1

ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml","applicationContext-test.xml"});

ApplicationContext ac = new ClassPathXmlApplicationContext("classpath*:/applicationContext*.xml");

ApplicationContext ac = new ClassPathXmlApplicationContext("classpath*:src/folder/applicationContext*.xml");

 

2

ApplicationContext ac = new FileSystemXmlApplicationContext("WebRoot/WEB-INF/applicationContext.xml");

ApplicationContext ac = new FileSystemXmlApplicationContext("file:D:/workspace/testproject/WebRoot/WEB-INF/applicationContext.xml");

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值