【发布时间】:2014-11-27 15:36:48
【问题描述】:
我知道我的 main-servlet.xml 中的 bean 在子上下文中。根据研究,我知道我可以通过 WebApplicationContextUtils 在 GreetingController 中获取根 ApplicationContext。我会得到 null 因为我没有在 web.xml 中定义这样的根上下文。
现在我的问题是如何在没有 @AutoWired 注释的情况下获取子上下文并执行类似 childContext.getBean("forfun") 的操作,我想我已经对其进行了测试并且它可以工作;
提前感谢您的阅读和信息。
编辑:自动连接 ApplicationContext 或实现 ApplicationContextAware 将帮助您获取子应用程序上下文和根应用程序上下文。
Edit2:我找到了另一种获取defaultdispacher创建的上下文的方法,该上下文实际上存储在名为org.springframework.web.servlet.FrameworkServlet.CONTEXT.(servletName)的servletcontext属性中
假设您的默认 servlet 是 main,您可以使用以下代码通过 defaultdispacher[main-servlet.xml] 获取上下文 craete。ApplicationContext context1=(WebApplicationContext) request.getSession().getServletContext().getAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.main")
但还是不明白为什么在 WebApplicationContextUtils 方法中我们不能访问子上下文。
web.xml 文件
<webapp>
<servlet>
<servlet-name>main</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/main-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>main</servlet-name>
<url-pattern>/main/*</url-pattern>
</servlet-mapping>
</web-app>
main-servlet.xml
<beans>
<bean name ="/testing/*" class="springmvc.GreetingController"></bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/Jsp/"
p:suffix=".jsp"/>
<bean id="forfun" class="springmvc.Foo"></bean>
</beans>
GreetingController.java
@Controller
public class GreetingController {
@AutoWired
Foo forfun;//this works even if forfun is defined in main-servlet.xml
@RequestMapping("/testing")
public String testing(HttpServletRequest request){
ApplicationContext context =
WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
Foo f=(Foo) context.getBean("forfun");//supposed to work if i have it defined in root context
/*
I would something like this
ChildContext child = Utils.getChildContext(request);
Foo f=(Foo) child.getBean("forfun");
*/
return "test";
}
}
【问题讨论】:
-
为什么要通过
WebApplicationContext获得它? -
不是出于实际原因,只是尝试看看有没有办法。
标签: java spring spring-mvc servlets model-view-controller