欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

applicationContext获取

程序员文章站 2022-03-03 13:17:30
...

 

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");