In Spring MVC with annotation, we mark any POJO with @Controller. In this controller we can get WebApplicationContext, using autowired property.
@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";
}
But in this approach we do not have servletContext handy with us. So is there way we can still use older way of getting WebApplicationContext ? i.e.
WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)
How will we get servletContext here ?
I am not facing any compulsion to use old way; so this question is just out of curiosity to check flexibility of spring. Also It can be a interview question.
You can just inject it into your controller:
@Autowired private ServletContext servletContext;
Or take HttpServletRequest as a parameter and get it from there:
@RequestMapping(...)
public ModelAndView myMethod(HttpServletRequest request ...){
ServletContext servletContext = request.getServletContext()
}