[英]How to get the context instance of a web app. context?
I don't know exactly how to get the web application ctx. 我不确切地知道如何获取Web应用程序ctx。 instance within a Spring web application. Spring Web应用程序中的实例。 For ex We usually do the configuration like : 对于ex,我们通常进行如下配置:
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
...
}
I'm aware of the ApplicationContextAware, I've implemented it before. 我知道ApplicationContextAware,之前已经实现过。 The thing is it was implemented to get the Application context and not specifically Web application context. 问题是实现它是为了获取Application上下文,而不是Web应用程序上下文。 For ex : 对于前:
public class ApplicationContextProvider implements ApplicationContextAware{
private static ApplicationContext context;
public static ApplicationContext getApplicationContext() {
return context;
}
@Override
public void setApplicationContext(ApplicationContext ac)
throws BeansException {
context = ac;
}
}
And later in handler/controller classes I obtained it with smtg like this : 然后在处理程序/控制器类中,我通过smtg获得了它,如下所示:
MrBean tb = ApplicationContextProvider.getApplicationContext().getBean("MrBean", MrBean.class);
In this ex the context is not a web app. 在此情况下,上下文不是网络应用程序。 context rather than a global app. 上下文而不是全局应用程序。 context (not specifically a web context). 上下文(不是专门针对Web上下文)。 I need your help in retrieving the web context instance because I need to active some profiling beans already configured from the configuration. 在检索Web上下文实例时,需要您的帮助,因为我需要激活一些已经从配置中配置的性能分析bean。 Thanks in advance. 提前致谢。
If you have the HttpServletRequest
object you can retrieve the WebApplicationContext
via RequestContextUtils#findWebApplicationContext()
如果您拥有HttpServletRequest
对象,则可以通过RequestContextUtils#findWebApplicationContext()
检索WebApplicationContext
。
Look for the WebApplicationContext associated with the DispatcherServlet that has initiated request processing, and for the global context if none was found associated with the current request. 查找与已启动请求处理的DispatcherServlet关联的WebApplicationContext,以及是否找不到与当前请求关联的全局上下文。 The global context will be found via the ServletContext or via ContextLoader's current context. 全局上下文将通过ServletContext或ContextLoader的当前上下文找到。
NOTE: This variant requires Servlet 3.0+ and is generally recommended for forward-looking custom user code. 注意:此变体需要Servlet 3.0+,通常推荐用于前瞻性自定义用户代码。
Eg 例如
WebApplicationContext webApplicationContext = RequestContextUtils.findWebApplicationContext(request);
But this only works within spring mvc/webflow context because the Spring DispatcherServlet ensures that the WebApplicationContext instance is available in the currently running thread. 但这仅在spring mvc / webflow上下文中有效,因为Spring DispatcherServlet确保WebApplicationContext实例在当前运行的线程中可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.