Spring MVC: Model - View
Spring MVC: Model - View
Spring MVC: Model - View
Spring is widely used for creating scalable applications. For web applications Spring
provides Spring MVC framework which is a widely used module of spring which is used
to create scalable web applications. Spring MVC framework enables the separation of
modules namely Model View, Controller, and seamlessly handles the application
integration. This enables the developer to create complex applications also using plain
java classes. The model object can be passed between view and controller using maps.
• Front Controller –
It remains responsible for managing the flow of the web application. Dispatcher
Servlet acts as a front controller in Spring MVC.
The above diagram shows that each layer of the architecture is directly communicating
with the layer just above or below it, is because of the workflow. It means each layer only
depends on its adjacent layer, so if we change the API of one layer, we just need to update
the layers adjacent to it.
The brief description of the layers is given below.
1. Presentation layer
It is the front layer or top layer of the architecture, as it consists of views. It is used to
translate the JSON fields to objects and vice-versa, and also handles authentication and
HTTP requests. After completing the authentication, it passes it to the business layer for
further processes.
2. Business Layer
It handles all the business logic and also performs validation and authorization as it is a
part of business logic. For example, only admins are allowed to modify the user’s account.
3. Persistence Layer
It contains all the storage logic, such as database queries of the application. It also
translates the business objects from and to database rows.
4. Database Layer
The database layer consists of the database such as MySQL, Postgre, MongoDB, etc. It may
contain multiple databases. All the database related operations like CRUD (Create,
Read/Retrieve, Update, and Delete) are performed in this layer.
The Spring Boot architecture is based on the Spring framework. So, it mostly uses all the
features and modules of Spring-like Spring MVC, Spring Core, etc., except that there is no
need for the DAO and DAOImpl classes.
The following diagram shows the workflow of Spring Boot.
@EnableAutoConfiguration
@EnableAutoConfiguration enables auto-configuration of beans present in the
classpath in Spring Boot applications. In a nutshell, this annotation enables Spring
Boot to auto-configure the application context. Therefore, it automatically creates
and registers beans that are part of the included jar file in the classpath and also the
beans defined by us in the application. For example, while creating a Spring Boot
starter project when we select Spring Web and Spring Security dependency in our
classpath, Spring Boot auto-configures Tomcat, Spring MVC and Spring Security for
us.
Moreover, Spring Boot considers the package of the class declaring
the @EnableAutoConfiguration as the default package. Therefore, if we apply this
annotation in the root package of the application, every sub-packages & classes will
be scanned. As a result, we won’t need to explicitly declare the package names
using @ComponentScan.
Furthermore, @EnableAutoConfiguration provides us two attributes to manually exclude
classes from auto-configurations. If we don’t want some classes to be auto-
configured, we can use exclude attribute to disable them. Another attribute is
excludeName to declare a fully qualified list of classes to exclude. For example,
below are the codes.
Use of ‘exclude’ in @EnableAutoConfiguration
@Configuration
@EnableAutoConfiguration(exclude={WebSocketMessagingAutoConfiguration.class})
public class MyWebSocketApplication {
public static void main(String[] args) {
...
}
}
Use of ‘excludeName’ in @EnableAutoConfiguration
@Configuration
@EnableAutoConfiguration(excludeName =
{"org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoCon
figuration"})
public class MyWebSocketApplication {
public static void main(String[] args) {
...
}
}
@ConfigurationProperties
Spring Framework provides various ways to inject values from the properties file.
One of them is by using @Value annotation. Another one is by
using @ConfigurationProperties on a configuration bean to inject properties values to a
bean. But what is the difference among both ways and what are the benefits of
using @ConfigurationProperties, you will understand it at the end. Now Let’s see how to
use @ConfigurationProperties annotation to inject properties values from the
application.properties or any other properties file of your own choice.
First, let’s define some properties in our application.properties file as follows. Let’s
assume that we are defining some properties of our development working
environment. Therefore, representing properties name with prefix ‘dev’.
dev.name=Development Application
dev.port=8090
dev.dburl=mongodb://mongodb.example.com:27017/
dev.dbname=employeeDB
dev.dbuser=admin
dev.dbpassword=admin
Now, create a bean class with getter and setter methods and annotate it with
@ConfigurationProperties.
@ConfigurationProperties(prefix="dev")
public class MyDevAppProperties {
private String name;
private int port;
private String dburl;
private String dbname;
private String dbuser;
private String dbpassword;
@Autowired
private MyDevAppProperties devProperties;
@Override
public void run(String... args) throws Exception {
System.out.println("App Name = " + devProperties.getName());
System.out.println("DB Url = " + devProperties.getDburl());
System.out.println("DB User = " + devProperties.getDbuser());
}
}
We can also use the @ConfigurationProperties annotation on @Bean-annotated
methods.
@Configuration
We apply this annotation on classes. When we apply this to a class, that class will act
as a configuration by itself. Generally the class annotated with @Configuration has
bean definitions as an alternative to <bean/> tag of an XML configuration. It also
represents a configuration using Java class. Moreover the class will have methods to
instantiate and configure the dependencies. For example :
@Configuration
public class AppConfig {
@Bean
public RestTemplate getRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
return restTemplate();
}
}
♥ The benefit of creating an object via this method is that you will have only one
instance of it. You don’t need to create the object multiple times when required.
Now you can call it anywhere in your code.
@Bean
We use @Bean at method level. If you remember the xml configuration of a Spring, It
is a direct analog of the XML <bean/> element. It creates Spring beans and generally
used with @Configuration. As aforementioned, a class with @Configuration (we can call
it as a Configuration class) will have methods to instantiate objects and configure
dependencies. Such methods will have @Bean annotation. By default, the bean name
will be the same as the method name. It instantiates and returns the actual bean. The
annotated method produces a bean managed by the Spring IoC container.
@Configuration
public class AppConfig {
@Bean
public Employee employee() {
return new Employee();
}
@Bean
public Address address() {
return new Address();
}
}
For comparison sake, the configuration above is exactly equivalent to the following
Spring XML:
<beans>
<bean name="employee" class="com.dev.Employee"/>
<bean name="address" class="com.dev.Address"/>
</beans>
The annotation supports most of the attributes offered by <bean/>, such as: init-
method, destroy-method, autowiring, lazy-init, dependency-check, depends-
on and scope.
@Component
This is a generic stereotype annotation which indicates that the class is a Spring-
managed bean/component. @Component is a class level annotation. Other
stereotypes are a specialization of @Component. During the component scanning,
Spring Framework automatically discovers the classes annotated with @Component, It
registers them into the Application Context as a Spring Bean.
Applying @Component annotation on a class means that we are marking the class to
work as Spring-managed bean/component. For example, look at the code below:
@Component
class MyBean { }
On writing a class like above, Spring will create a bean instance with name ‘myBean’.
Please keep in mind that, By default, the bean instances of this class have the same
name as the class name with a lowercase initial. However, we can explicitly specify a
different name using the optional argument of this annotation like below.
@Component("myTestBean")
class MyBean { }
@Controller
@Controller tells Spring Framework that the class annotated with @Controller will work
as a controller in the Spring MVC project.
@RestController
@RestController tells Spring Framework that the class annotated
with @RestController will work as a controller in a Spring REST project.
@Service
@Service tells Spring Framework that the class annotated with @Service is a part of
service layer and it will include business logics of the application.
@Repository
@Repository tells Spring Framework that the class annotated with @Repository is a
part of data access layer and it will include logics of accessing data from the
database in the application.
Configuration Annotations
Next annotations in our article ‘Spring Boot Annotations with Examples’ are for
Configurations. Since Spring Framework is healthy in configurations, we can’t avoid
learning annotations on configurations. No doubt, they save us from complex coding
effort.
@ComponentScan
Spring container detects Spring managed components with the help
of @ComponentScan. Once you use this annotation, you tell the Spring container
where to look for Spring components. When a Spring application starts, Spring
container needs the information to locate and register all the Spring components
with the application context. However It can auto scan all classes annotated with the
stereotype annotations such as @Component, @Controller, @Service,
and @Repository from pre-defined project packages.
The @ComponentScan annotation is used with the @Configuration annotation to ask Spring the packages
to scan for annotated components. @ComponentScan is also used to specify base packages and base
package classes using basePackages or basePackageClasses attributes of @ComponentScan. For example :
import com.springframework.javatechonline.example.package2.Bean1;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages =
{"com.springframework.javatechonline.example.package1",
"com.springframework.javatechonline.example.package3",
"com.springframework.javatechonline.example.package4"},
basePackageClasses = Bean1.class
)
public class SpringApplicationComponentScanExample {
....
}
Here the @ComponentScan annotation uses the basePackages attribute to specify
three packages including their subpackages that will be scanned by the Spring
container. Moreover the annotation also uses the basePackageClasses attribute to
declare the Bean1 class, whose package Spring Boot will scan.
Moreover, In a Spring Boot project, we typically apply the @SpringBootApplication
annotation on the main application class. Internally, @SpringBootApplication is a
combination of the @Configuration,
@ComponentScan, and @EnableAutoConfiguration annotations. Further, with this default
setting, Spring Boot will auto scan for components in the current package
(containing the SpringBoot main class) and its sub packages.
@Import
Suppose we have multiple Java configuration classes annotated
by @Configuration. @Import imports one or more Java configuration classes. Moreover
It has the capability to group multiple configuration classes. We use this annotation
where one @Configuration class logically imports the bean definitions defined by
another. For example:
@Configuration
@Import({ DataSourceConfig.class, TransactionConfig.class })
public class AppConfig extends ConfigurationSupport {
// @Bean methods here that can reference @Bean methods in DataSourceConfig or
TransactionConfig
}
1. Basic Setup
@SpringBootApplication
Java
Copy
package com.example.demo;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootAppli
cation;
@SpringBootApplication
public class DemoApplication {
}
It’s not much of a Hello World though, as it doesn’t actually
display anything. For that, let’s introduce @RestController and
@GetMapping. But before that, let’s talk about the annotations
that @SpringBootApplication replaces.
@Configuration
Now superseded by @SpringBootApplication,
@Configuration enables Java configuration and lets you
use Spring Beans in the class.
@ComponentScan
Also superseded by @SpringBootApplication, @ComponentScan
enables component scanning and means controller classes and
components you create can be discovered by the framework. It
marks classes to be discovered with @Controller.
@EnableAutoConfiguration
The final annotation replaced by @SpringBootApplication,
@EnableAutoConfiguration enables Spring Boot’s
autoconfiguration. Spring Boot makes over 200 decisions for you.
These can be overridden if you want to make your own choices,
but it will pick sensible defaults for you, saving you a lot of
time at the beginning of projects.
@GetMapping
Take a look at your earlier Hello World and get it returning a
response.
package com.example.demo;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootAppli
cation;
import
org.springframework.web.bind.annotation.GetMapping;
import
org.springframework.web.bind.annotation.RequestParam;
import
org.springframework.web.bind.annotation.RestController
;
@SpringBootApplication
@RestController
public class DemoApplication {
@GetMapping("/hello")
public String hello(@RequestParam(value = "name",
defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
}
@RequestMapping
This can combine with @Controller to create a class that
returns simple requests, such as the following code:
@Controller
@RequestMapping("users")
public class UserController {
@GetMapping("/{id}", produces =
"application/json")
public @ResponseBody User getUser(@PathVariable
int id) {
return findUsersById(id);
}
3. Component Types
There are several annotations to let you label components in
your application. Aside from @RestController, these are
functionally identical, but allow you to organize your application
and mark classes for specific roles, helping to keep your
application modular.
@Component
Application components and their variants are automatically
registered as Spring Beans, providing dependency injection,
provided you use either @SpringBootApplication or
@ComponentScan.
@Service
This is an alternative to @Component that specifies you intend
to use the class as part of your service layer. However, it doesn’t
actually implement anything differently than @Component.
@Repository
This annotation marks a class as part of your data layer,
for handling storage, retrieval, and search. This can be especially
useful for targeting your tests and generating the right
exceptions.
@Controller
@Controller is a specialized @Component marked as a
controller in MVC architecture.
@RestController
@RestController combines the @Controller and @ResponseBody
into a single annotation. @RestController classes return domains
instead of views.
4. Testing
As it should, Spring Boot makes it very easy to write
tests. Identifying and fixing errors is much easier when the
framework helps you.
@SpringBootTest
Though Spring Boot can use regular Spring tests using the @Test
annotation, it has a special annotation—@SpringBootTest—that
lets you test using Spring Boot specific features.
@SpringBootTest(properties = "spring.main.web-
application-type=reactive")
class YourTests {
// code here
}
@MockBean
The @MockBean annotation allows you to create a temporary
version of a service for testing. It’s useful if you have a web
service you connect to that isn’t suitable for testing, or if you
want to test against specific results.
Here’s an example, based on Spring Boot’s documentation.
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.*;
import org.springframework.boot.test.context.*;
import org.springframework.boot.test.mock.mockito.*;
@SpringBootTest
class ServiceTests {
@MockBean
private RemoteService remoteService;
@Autowired
private Capitalizer capitalizer;
@Test
void exampleTest() {
// RemoteService has been injected into the
capitalizer bean
given(this.remoteService.testCall()).willReturn("test
");
String caps = capitalizer.capitalizeTestCall();
assertThat(caps).isEqualTo("TEST");
}
}
@Validated
To validate input for methods, you apply the @Validated
annotation to the class. For nested properties, apply the @Valid
tag.
import javax.validation.constraints.Size;
import javax.validation.constraints.NotNull;
import org.springframework.stereotype.Service;
import
org.springframework.validation.annotation.Validated;
@Service
@Validated
public class TestBean {
public Archive findByCopiesAndTitle(@Size(min = 1, max
= 100) String code, @NotNull Title title) {
return …
}
}
Jackson ObjectMapper Tutorial
In this tutorial, you will learn how to use Jackson ObjectMapper with Spring Boot
application to serialize and deserialize Java objects.
Overview
In today’s time, the JSON format is one of the most popular formats to transfer
and exchange data on the world wide web. Almost all RESTful web services
support JSON as input and output structure. Additionally, It is also widely used by
various NoSQL databases such as MongoDB to store records as well.
In this tutorial, we’ll deep-dive into Jackson ObjectMapper and discuss how to
serialize JSON requests and responses in the Spring Boot application with
various Jackson configurations.
Preparation:
• JDK 1.8
• Intellij Idea for IDE
• Maven
• Springboot Application version 2.5.5
• Lombok
1. Project Setup
2. Introducing Jackson ObjectMapper
After importing the project into IDE, we will be creating the following sub-
packages inside our main package
‘com.appsdeveloperblog.ObjectMapperTutorial‘ :
In the end, the final project structure will look like this:
Maven Dependencies
We will only include spring-boot-starter-web and Lombok dependencies in our
pom.xml. As, Spring Boot already provides managed dependencies for various
Jackson modules. For example,
• jackson-core
• jackson-databind
• jackson-annotations
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.0</version>
<relativePath/>
</parent>
<groupId>com.appsdeveloperblog.ObjectMapperTutorial</groupId>
<artifactId>Spring-boot-custom-JSON</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>11</java.version>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package com.appsdeveloperblog.ObjectMapperTutorial.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
return employees;
Create Controller
Next, we need the controller for GET and POST services.
The complete source code for “EmployeeController.java” is as follow:
package com.appsdeveloperblog.ObjectMapperTutorial.controller;
import com.appsdeveloperblog.ObjectMapperTutorial.model.Employee;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/getEmployees")
return Employee.getEmployee();
@PostMapping("/createEmployees")
@ResponseBody
employee.setID(employee.getID() + 100);
return employee;
}
Running the Application
Now, we can create the main class to start the Spring Boot Application:
package com.appsdeveloperblog.ObjectMapperTutorial;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
SpringApplication.run(SpringBootCustomJsonApplication.class, args);
In the end, we will run our application either via executing the following command
or using the ‘Run’ button from IDE. You will find that the application started on
Tomcat port 8080.
http://localhost:8080/getEmployees
Similarly, if we do POST call using the below URL via Postman we should get the
following response.
http://localhost:8080/createEmployees
This process is called Serialization because spring converted the list of employee
object to JSON.
Customizing ObjectMapper
In this section, we’ll learn how to customize the
default ObjectMapper behaviour so based on requirement we can change the
Serialization/Deserialization.
Example 1:
package com.appsdeveloperblog.ObjectMapperTutorial.config;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
@Configuration
class WebConfig {
@Bean
@Primary
.indentOutput(true)
.serializationInclusion(JsonInclude.Include.NON_NULL)
.propertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE)
.build();
}
}
Now if we run our project again and execute GET /getEmployees , we will see the
following output.
Example 2:
Sometimes we have a use-case, where API send additional field JSON than
expected in the internal java objects structure. In this case, we can use the
ObjectMapper feature to have stricter checks during serialization to throw
exceptions on such cases.
package com.appsdeveloperblog.ObjectMapperTutorial.config;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
@Configuration
class WebConfig {
@Bean
@Primary
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
return objectMapper;
There are many such properties that can be configured on ObjectMapper, you
can follow official Javadoc for Jackson-databind features here.
//System.out.println(json);
} catch (JsonProcessingException e) {
e.printStackTrace();
emp.setfirstName("David");
emp.setjobTitle("Associate");
emp.gender("Male");
try {
//System.out.println(json);
} Catch (JsonProcessingException e) {
e.printStackTrace();
}
1. Lambda Expressions
Lambda expressions are known to many of us who have worked on other
popular programming languages like Scala. In Java programming language, a
Lambda expression (or function) is just an anonymous function, i.e., a function
with no name and without being bound to an identifier.
1.1. Syntax
A few basic syntaxes of lambda expressions are:
() -> expression
Also, since default methods are not abstract , we can add default methods to
the functional interface as many as we need.
@FunctionalInterface
@Override
public String toString(); //Overridden from Object class
@Override
public boolean equals(Object obj); //Overridden from Object class
}
System.out.println("I am moving");
tiger.move();
Output: I am moving
If the class willingly wants to customize the behavior of move() method then it
can provide its own custom implementation and override the method.