Java 如何获取默认的 WebApplicationContext?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2495741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the default WebApplicationContext?
提问by Walker
I need the context to ApplicationContext.xml
,which I provided in web.xml
as
我需要的背景下ApplicationContext.xml
,这是我所提供web.xml
的
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
But I need a control for this in Controller
class.
但我需要在Controller
课堂上对此进行控制。
I tried many things including
我尝试了很多东西,包括
WebApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext();
but it doesnt help.
但它没有帮助。
采纳答案by skaffman
Easiest solution is to use getWebApplicationContext()
of WebApplicationContextUtils
:
最简单的解决方案是使用getWebApplicationContext()
的WebApplicationContextUtils
:
Find the root WebApplicationContext for this web application, which is typically loaded via ContextLoaderListener.
找到此 Web 应用程序的根 WebApplicationContext,它通常通过 ContextLoaderListener 加载。
See also getRequiredWebApplicationContext()
.
回答by Chidveer
RequestContextUtilswill be the best choice as, even if you have multiple WebAppContexts it will get the current active one.
RequestContextUtils将是最佳选择,因为即使您有多个 WebAppContexts,它也会获得当前活动的一个。