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?
CodePudding user response:
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."
CodePudding user response:
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.