Spring MVC Tutorial
Core Spring MVC
Spring MVC - Annotation
Spring MVC - Form Handling
Spring MVC with JSTL
Spring MVC with REST API
Spring MVC with Database
In Spring, both ApplicationContext
and WebApplicationContext
are interfaces responsible for providing configuration information to the application. They hold the references to beans and configurations defined in your Spring application. However, they have distinct roles and features based on where they're used:
ApplicationContext:
WebApplicationContext:
ApplicationContext
tailored for web applications. It's tied to the lifecycle of a web application.ServletContext
(i.e., a web application in a Servlet container like Tomcat).ApplicationContext
offers, it adds functionalities that are specific to web applications.ServletContext
, etc.request
, session
, or application/globalsession
.WebApplicationContext
extends ApplicationContext
. So, everything you can do with ApplicationContext
, you can also do with WebApplicationContext
.
In a Spring MVC application, typically, there's a root ApplicationContext
and then a child WebApplicationContext
for each Spring DispatcherServlet
. The root context is for shared beans (like services, repositories, etc.), and the child context is for web-specific beans (like controllers, view resolvers, etc.).
While both ApplicationContext
and WebApplicationContext
provide access to application configurations and beans, WebApplicationContext
is specialized for web applications, understanding web-related scopes and the structure of a web application. On the other hand, ApplicationContext
is more general-purpose, suitable for all types of applications.
ApplicationContext in Spring MVC example:
Define the root context in your web.xml
:
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
In applicationContext.xml
, you define global beans:
<beans> <!-- Define global beans --> </beans>
WebApplicationContext configuration in Spring MVC:
Configure the WebApplicationContext for each servlet in the web.xml
:
<servlet> <servlet-name>myServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/myServlet-servlet.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>myServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
In myServlet-servlet.xml
, you define servlet-specific beans:
<beans> <!-- Define beans specific to the servlet --> </beans>