简体   繁体   中英

What is the WebApplicationContext in Spring MVC? What is it used for?

I know what the Spring ApplicationContext is, but I'm confused about the WebApplicationContext from Spring MVC. Can you guys help me?

  • What is the WebApplicationContext?
  • Why is it necessary?
  • What is it used for?

You can checkout WebApplicationContext codes for insight:

public interface WebApplicationContext extends ApplicationContext {

   ServletContext getServletContext();
}

Because of the inheritance, you can simply think that WebApplicationContext is just a special kind of ApplicationContext which is used for the web application only. So all things that can be done by the ApplicationContext can also be done by the WebApplicationContext . But WebApplicationContext just provides one extra function which allow you to access the underlying ServletContext defined by the Servlet API specification.

It is necessary mainly because of the good OOP design. If we do not divide it into two interfaces but just add getServletContext() to the ApplicationContext and use it for all the non-web and web applications, it is awkward that the for the non-web application, we still need to include the Servlet API JAR to our project because we makes ApplicationContext depends on Servlet API.

The official Spring documentation contains the answer.

The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features necessary for web applications. It differs from a normal ApplicationContext in that it is capable of resolving themes (see Using themes), and that it knows which Servlet it is associated with (by having a link to the ServletContext). The WebApplicationContext is bound in the ServletContext, and by using static methods on the RequestContextUtils class you can always look up the WebApplicationContext if you need access to it.

It is used to facilitate web server functionality. Documentation also goes on to mention special beans types the WebApplicationContext provides. For example, a MultiPartResolver that "parses multi-part requests for example to support processing file uploads from HTML forms."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM