Explain Codes LogoExplain Codes Logo

Difference between applicationContext.xml and spring-servlet.xml in Spring Framework

java
spring-framework
applicationcontext
spring-servlet
Nikita BarsukovbyNikita Barsukov·Jan 1, 2025
TLDR

The applicationContext.xml file serves as a central hub for backend configurations like services and data access layers. On the other hand, spring-servlet.xml handles the frontend part, specific to the Spring MVC web layer like controllers and view resolvers.

  • applicationContext.xml: beans for backend (services, repositories).
  • spring-servlet.xml: beans for frontend (controllers, view resolvers).
<!-- In applicationContext.xml --> <bean id="userService" class="com.example.UserService"/> <!-- where the magic happens --> <!-- In spring-servlet.xml --> <bean id="userController" class="com.example.web.UserController"/> <!-- Here's Johnny(Controller)! -->

Parent-Child Relationship: Allegory of applicationContext.xml and spring-servlet.xml

Every servlet in Spring has its application context file - spring-servlet.xml. It's specific to one servlet's MVC interactions, while applicationContext.xml is shared among all servlets.

Visualizing Context Relationship

Picture it this way: 🏙️ applicationContext.xml: ├─ 🛣️ Infrastructure: Shared services (universal access). └─ 🌳 Global settings: Security configs (boundary control). 🛍️ spring-servlet.xml: └─ 🍨 Servlet specifics: MVC components (flavor of the day).

The Nitty-Gritty of applicationContext.xml and spring-servlet.xml

Separation of Concerns and Hierarchical Contexts

Configured as a parent-child hierarchy, applicationContext.xml deals with shared backend services while spring-servlet.xml is servlet-specific, focusing on MVC components. A child may have, but the parent may not, access to the child's declarations. 🔑 to a modular application!

What goes where?

To keep your MVC life stylishly isolated, load spring-servlet.xml with controller scans and mappings. Save applicationContext.xml for backend services, data access - it's the Swiss army knife for your Spring app, and can be your debugging friend too! 👾🔒

Order of Bean Instantiation

Bean instantiation first happens in applicationContext.xml, followed by spring-servlet.xml. This order ensures dependencies are set up and ready when referenced by other servlets. First come, first serve, amirite? 🙈

Properties Files Accessibility

Properties files declared in applicationContext.xml might not be accessible by DispatcherServlet. It's like preparing a party 🎉 but forgetting to invite the guests! Always remember to check your context loader listener setup. ⚠️