在带有注解的 Spring MVC 中,我们使用 @Controller 标记任何 POJO。
在这个 Controller 中,我们可以使用 autowired 属性获取 WebApplicationContext。
@Controller
public class HomePageController {
@Autowired
ApplicationContext act;
@RequestMapping("/*.html")
public String handleBasic(){
SimpleDomain sd = (SimpleDomain)act.getBean("sd1");
System.out.println(sd.getFirstProp());
return "hello";
}
但是在这种方法中,我们没有方便的 servletContext。那么有没有办法我们仍然可以使用旧的方式来获取 WebApplicationContext ? IE。
WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)
我们将如何在这里获得 servletContext ?
我没有面临使用旧方式的任何强制;所以这个问题只是出于好奇来检查 Spring 的灵 active 。
也可以是面试题。
最佳答案
您可以将其注入(inject)您的 Controller :
@Autowired private ServletContext servletContext;
或者将 HttpServletRequest 作为参数并从那里获取:
@RequestMapping(...)
public ModelAndView myMethod(HttpServletRequest request ...){
ServletContext servletContext = request.getServletContext()
}
关于spring - 如何在类注解@controller 中获取Spring WebContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13206588/