In this chapter, you will learn about the key concepts of the Spring framework, and how we can use this framework to develop web applications. The following are some of the topics that will be dealt with:
- Introduction to the Spring IOC container
- Introduction to the Spring web MVC
- Building a
Hello World
web application with Spring Boot - Implementing controllers
- Handling request parameters
- Handler interceptors
- Handling responses
- Creating a RESTful Web Service
- Dockerizing Spring Boot Application
Starting with the section, Implementing controllers in this chapter, we will start building a sample healthcare web application to demonstrate the key concepts. The following are some of the key functionalities of the sample app which will be covered as part of building the app:
- Signup for doctors and patients
- Logging into the app
- Searching for doctors based on their specialties
- Fixing an appointment
- Interacting with the doctor
As a primer to learning the Spring Web MVC framework, it is recommended to learn some of the following object-oriented design principles, which act as a basis for the Spring Web framework. Note that these principles form a part of the famous Single responsibility, Open-closed, Liskov substitution, Interface segregation, and Dependency inversion (SOLID) principle by Robert Martin (Uncle Bob):
- Single Responsibility Principle (SIP): This principle states that a module, a class, or a method should have the responsibility of serving just one functionality of the underlying software. In other words, a module, a class or a method should have just one reason to change. Modules or classes following SIP have high cohesiveness, and thus, can be termed as reusable entities. Classes violating SIP are found to have high cyclomatic complexity, and thus, low testability.
- Open-Closed Principle (OCP): This principle states that the classes are open for extension, but closed for modification. Based on this principle, the core classes of the Spring Web MVC consist of some methods which are marked as final, which, essentially, means that these final methods can not be overridden with custom behavior.
- Liskov Substitution Principle (LSP): This principle states that if a class
A
(child class) is derived from classB
(parent class), then the object of classB
can be replaced by (or substituted with) an object of classA
without changing any of the properties of classB
. It can be inferred that the functions which use references of the base class must be able to use objects of the derived class without the need to know about the implementation of the base class. For example, let's consider the square and rectangle example. In the case where square derives from rectangle, then, as per LSP, an object of the classRectangle
can be substituted with an object of the classSquare
. However, in reality, this is not possible without doing appropriate implementation in theSquare
class setter methods, where setting either of length or breadth sets another side of equal length, and/or code using these classes do appropriate checks to find out whether the object is an instance of the classSquare
orRectangle
. - Interface Segregation Principle (ISP): This principle states that the fat interfaces having large number of API definitions should be split into smaller interfaces defining a set of cohesive APIs. Not following this principle leads to the client providing empty implementations for unwanted APIs.
- Dependency Inversion Principle (DIP): This principle is pretty much related to the IOC principle, which is discussed in the next section. It states that the dependency relationship between higher-level modules with low-level modules is reversed, thus making these modules independent of each other's implementation details.
Before we get into understanding what is Spring IOC Container, let us quickly learn what is IOC.
Many a times, the Hollywood principle of Don't call us, we will call you is used to explain the concept of Inversion of Control. In Hollywood, this is what one gets to hear after auditioning is done. If we apply this principle to the programming model, instead of the classes creating dependencies along with serving functionality, the dependencies are appropriately made available to the classes during runtime, and the classes just need to focus on delivering the functionality.
Simply speaking, Inversion of Control (IOC) is about inverting the flow of control that the traditional programming model used to have in terms of objects at the higher-level handling the creation and management of lower-level objects' (can also be termed as dependencies) life cycle. In the IOC programming model, higher-level objects rather receive one or more instances of these dependencies from the calling object or external framework. This is why IOC is also termed Dependency Injection, wherein the dependencies are injected appropriately, and, objects bother themselves solely with the program execution and not with the object creation. Inversion of Control is related to the object-oriented principle known as the Dependency Inversion Principle (DIP), coined by Robert Martin (Uncle Bob).
Let's take a look at the following code sample, which represents higher-level objects handling the creation of lower-level objects (dependencies):
Let us take a look at the class DrawWithIOC
, which accepts the implementation of the Shape
object in its public constructor. Note that the dependencies, such as different implementations of the Shape
object, are rather injected, and code just does the execution of business logic without bothering about creation of objects related to the different implementations of Shape
. Other alternatives to injecting the dependencies are passing arguments to a factory method of the class, or through properties that are set on the object instance:
A Spring IOC container is a framework which, basically, manages the life cycle of plain old Java objects (POJOs), and injects them into the application as required. Java objects define their dependencies using one of the following methods:
- Dependencies are passed as arguments to the
constructor
method of the object. See how the object is passed as an argument to theconstructor
method in the example cited in the previous section. - Dependencies are passed as arguments to the
setter
method of the object. - Dependencies are passed as arguments to a
factory
method of the object.
A Spring IOC container injects the dependencies after it creates the beans. Note the fact that dependencies are no longer managed by Java objects. They are rather managed and injected by the framework, and hence, Inversion of Control.
The following are the packages which are core to the IOC container:
org.springframework.beans
org.springframework.context
It is the interface, org.springframework.context.ApplicationContext
(sub-interface of the interface, BeanFactory
), which represents the Spring IOC container and is responsible for managing the life cycle of beans. The instructions related to creating, configuring, and assembling the objects is termed Configuration Metadata. The configuration metadata is often represented using Java annotations or XML. A Java application using Spring IOC Container is created by combining Business POJOs with the previously mentioned configuration metadata, and passing it on to the IOC Container (an instance of ApplicationContext
). The same is represented using the following diagram:

Figure 1: Java Application with Spring IOC Container
Let's illustrate the preceding diagram with an example. The following code represents how a service, namely, UserService
is instantiated using Spring IOC container in a Spring Boot web application. Notice how the annotation-based autowiring feature has been used to have ApplicationContext
autowired to the userService
field in this code:
In this section, we will learn the key elements of the Spring Web model-view-controller (Spring Web MVC) framework, and how to quickly get started with a Spring web application using the Spring Web MVC components. The following will be covered in detail in this section:
- Key building blocks of a Spring Web MVC application
- Introduction to the Dispatcher servlet
In this section, we will learn about the key building blocks of a Spring web MVC application. The following diagram represents the key building blocks:

Figure 2: Key building blocks of Spring web MVC framework
The following are the details in relation to the preceding diagram:
- Dispatcher servlet: Dispatcher servlet, also termed the front controller, is at the core of the Spring Web MVC framework. Simply speaking, the Dispatcher servlet determines which
controller
class and method needs to be called when a page request or an API request arrives. In addition, it sends the response using the appropriate JSP page or JSON/XML objects. It dispatches the incoming requests to the appropriate handlers (custom controllers) with different handler mappings. This is integrated with the Spring IOC container, which allows it to use all the features that the Spring framework provides. - Handler Mappings: Handler mappings are used to map the request URL with the appropriate handlers such as controllers. The Dispatcher servlet uses the handler mappings to determine the controllers which will process the incoming requests. The handler mappings are specified in the XML file, or as annotations such as
@RequestMapping
,@GetMapping
, or@PostMapping
, and so on. The following diagram represents the@RequestMapping
annotation that is used for URL mapping. - Handler Interceptors: Handler interceptors are used to invoke preprocessing and post-processing logic before and after the invocation of the actual handler method respectively.
- Controllers: These are custom controllers created by the developers and used for processing the incoming requests. The controllers are tagged with annotations such as
@Controller
or@RestController
. Controllers are used to access the application behavior through one or more service interfaces. Controllers are used to interpret the user input, pass them to the services for implementation of business logic, and transform the service output into a model which is presented to the user as a view. The following diagram shows the@Controller
annotation which represents theDemoApplication
class to play the role of a controller:

Figure 3: Representing handler mappings (URL mapping) and Controller annotation
- Services: These are the components coded by the developers. These components contain the business logic. One or more methods of services are invoked from within the
Controller
methods. Spring provides annotations such as@Service
for identifying services. The following code represents the service classUserService
, which consists of a method,getUsername
. Pay attention to the@Service
annotation. Note how the instance ofUserService
is defined in@Controller
, as shown in the preceding code, and the methodgetUsername
is invoked on the instance ofUserService
.
- Data Access Objects (DAO): The classes which represent DOA, are used to do data processing with the underlying data sources. These classes are annotated with annotations such as
@Repository
. The preceding code ofUserService
consists, a DAO, namely,UserDAO
. Note the@Repository
annotation used by the class,UserDAO
, in the following code:
- View Resolvers: View resolvers are components which map view names to views. They help in rendering models in the browser based on different view technologies such as JSP, FreeMarker, JasperResports, Tiles, Velocity, XML, and so on. Spring comes with different view resolvers such as
InternalResourceViewResolver
,ResourceBundleViewResolver
,XMLViewResolver
, and others. View resolvers are used by the Dispatcher servlet to invoke the appropriate view components. - Views: Views are used to render the response data on the UI. They can be represented using different technologies such as JSP, Velocity, Tiles, and so on.
In this section, we will learn about the core component of a Spring web MVC application, the Dispatcher servlet.
As introduced in the previous section, Dispatcher servlet is the front controller which processes the user requests by invoking the appropriate components such as handler mappings, interceptors, adapters, custom controllers, services, DOA, view resolver, and finally, the views. The following diagram represents the web request/response workflow of the Dispatcher servlet:

Figure 4: Web request/response flow across the Dispatcher servlet
As per the preceding diagram, the journey of a request/response through a Spring web MVC application looks like the following:
- The user requests arrive at the server, and are intercepted by the Dispatcher servlet.
- The Dispatcher servlet gets a handler object (primarily, an instance of
HandlerExecutionChain
) from theHandlerMapping
object based on the URL mapping. URL mappings can be defined with theweb.xml
file or as annotations on the Controllers' methods.
- One or more instances of the
HandlerInterceptor
objects are retrieved from the handler object, and preprocessing logic is processed on the request object. - The instance of
HandlerAdapter
is retrieved from the handler object, and thehandle
method is invoked. This results in execution of logic within thecontroller
class. In the preceding diagram (Figure 3), the request withRequestMapping
as "/
" leads to the execution of code within thehome
method as part of this step. - The post-processing logic on the
HandlerInterceptor
instances is executed. This is the final step before therendering
method is invoked. - The
ViewResolver
instance is used to retrieve the appropriate view component. - The
render
method is invoked on the instance of view.