Spring Boot Knowledgebase (Part 1)

Tariqul Islam
10 min readFeb 5, 2020

What Are the Differences Between Spring and Spring Boot?

Spring comes with multiple features that make the developer’s life easy. The feature includes an embedded web server, auto-configure development environment, data persistence, and binding, annotations classes, dependency injection, aspect-oriented programming, easy security implementation.

On the other hand, spring has grown more and more complex day by day, the manual configuration can make developer life like hell. To solve this problem spring framework introduces the spring boot framework.

In Spring boot, Most of the platform and libraries are auto-configured, a developer can easily start their works.

Important features of the spring boot application are:

  • Auto-configure the application dependency to compile and run based on the artifacts, which are found on the classpath of the application.
  • Provide lots of non-functional features in a production environment, such as security or health checks

How Can We Set up a Spring Boot Application with Maven?

First, we have to add the spring-boot-starter-parent project or package in a maven project and declare dependencies that are needed for run Spring Boot application. There are steps need to do for setup the spring boot project in maven application

Add spring-boot-starter-parent project to the parent element in pom.xml:

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
</parent>

In the Dependency section, we have to add the following dependency also in pom.xml

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>

Then add the Following plugins dependency to the plugins section of pom.xml file

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

Then add the following code to the main class of the project

import org.springframework.boot.SpringApplication;@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(StarterApplication.class, args);
}
}

Then go to IDE, re-import all the project dependency. clean and build the maven project as a spring boot project.

Why do we need spring-boot-maven-plugin?

spring-boot-maven-plugin helps the developer to package and build the project, provide the code as jar and war format, so the developer can deploy the application in production.

Discuss spring-boot-maven-plugin command

spring-boot: run (run the spring boot application)
spring-boot: repackage
(repackage the application as jar or war
format)
spring-boot: start |
spring-boot: stop |
those two manage the lifecycle of the spring bootapplication and helping the test the application using integration testing
spring-boot: build-info (generate the build information which will help the actuator process the application status)

What Embedded Servers?

Embedded server means for spring boot is web server is part of the application so no need to install and deploy the application to a web server.

For Java web application normally we using the following steps to deploy the Embedded Server

Step 1: Install Java
Step 2: Install Web Server(Tomcat/Websphere/WebLogic)
Step 3: Deploy the application war file to Web server

Sometimes deployment java web application to the server create dependency mismatched issue for tools, packages and other features of web server, It is so painful for the developer to solve and configure the webserver problem Individually. So to simplify the project deployment embedded server idea comes in handy.

So for a Spring Boot Application, developer can generate an application jar with Embedded Tomcat. So web application as a normal Java application!

How to Deploy Spring Boot Web Applications as Jar and War Files?

To deploy the application as JAR and WAR file, it uses spring-boot-maven-plugin, to package a web application as an executable JAR and WAR file.

  1. Add the plugin to pom.xml:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

Then define which format of file we need to packaging for the Java web application.

If we want JAR file, so we need to specify the jar in packaging section of the pom.xml file

<packaging>jar</packaging>

Add the webserver dependency to dependency section in pom.xml file

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId
<scope>provided</scope>
</dependency>

If you want only war file to deploy the project with an external server, you need to specify war as in packaging section of the pom.xml file

<packaging>war</packaging>

How To access the properties value in Spring boot at Class and Models and controller?

@Value annotation is used to get external access to the properties

How Could we externalize source for configuration in Spring Boot?

  1. Using Application Properties (application.properties)
  2. Command-line properties (Convert the argument to properties and add them to set environment properties)
  3. Profile-specific properties — these properties are loaded from the application-{profile}.properties or its YML file

What is the spring Actuator?

Spring Actuator is a package of the spring boot framework. it includes the feature, which developer can use to manage and monitor the spring boot application. if we want to get the production-ready feature in an application, we should use the spring boot actuator.

Describe the Spring Actuator features?

Three main feature of the actuator is

  1. Endpoint: endpoint allows the developer to monitor and interact with the application. for example, the /health endpoint provides the basic health information of the application. /actuator/health
  2. Metrics: it provides dimensional metrics by integrating the micrometer. it provides the timers, gauges, counter, distribution summary and long task timer with dimensional data
  3. Audit: Spring provides a flexible audit framework that publishes events to an audit event repository.

What is the minimum requirement of spring boot to run in JVM?

Java 8+
Spring framework 5.1.9+

What is spring boot DevTools?

Spring boot DevTools is set to tools used for making the development process easier, which is automatically disabled in production mode.

Describe the septs of connecting to JDBC driver by Spring Boot?

Add the dependency to pom.xml file

<!-- MySQL JDBC driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

For Gradle

// https://mvnrepository.com/artifact/mysql/mysql-connector-java
compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.19'
  1. Declare the properties in applications.properties
spring.datasource.url =jdbc:mysql://localhost:3306/testapp?useSSL=false
spring.datasource.username
=root
spring.datasource.password
=ronnie
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.jpa.hibernate.ddl-auto
= update
logging.level.org.hibernate.SQL= DEBUG
logging.level.org.hibernate.type
=TRACE

Using the JDBC template to service and controller and other classes

import org.springframework.jdbc.core.JdbcTemplate;public class EmployeeDao {private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

public int saveEmployee(Employee e){
String query="insert into employee values( '"+e.getId()+"',
'"+e.getName()+"',
'"+e.getSalary()+"')";
return jdbcTemplate.update(query);
}
}

How To enable Http2 support in Spring Boot Application?

In application.properties add this following lines

server.http2.enable = true

What is the @RequestMapping annotation in spring boot?

This annotation is used to provide the routing information and tells to spring that any HTTP request must be mapped to the respective method

To import this annotation we have to import the library of “org.springframework.web.bind.annotation.RequestMapping”

What is @RestController annotation in spring boot?

It tells the spring that, this class is a Rest Controller which is also annotated with other annotation class, which include @Controller and @RequestBody and @ResponseBody .

This annotation is used to create RESTful web service, os It takes care of mapping request data to the defined request handler method. when the response body generated from the handler method, it converts it to JSON or XML format.

What is Spring Boot CLI and How it works?

Spring boot CLI is a spring boot software tool, which is used to run and test the Spring Boot application from the command prompt.

1. Download Spring CLI, extract the folder
2. Set the Path to environment by `bin` folder
3. Check the version in terminal by “spring -version”

Example Code for Spring Boot Groovy Template

@RestController
class HelloWorld {
@RequestMapping(“/“)
String hello() {
“Hello world”
}
}

Then run the command from the command line

spring run <Spring_Groovy-ScriptName>

Difference Between JPA and Hibernate?

JPA is a Data Access Abstraction Layer to reduce the amount of boilerplate code.

Hibernate is an implementation of java persistence API and offers benefits of loose coupling.

How to create the custom endpoint in the spring boot actuator?

To create the custom actuator endpoint in Spring Boot 2.x, the developer needs to use @Endpoint annotation. Or also can use @WebEndpointor

What is Spring Data?

Spring Data aims to make it easy for the developer to use the relational and non-relational database, cloud-based data service and other data access technologies and basically, it makes it was for data access.

What is auto-configuration in spring boot?

Auto-configuration is used to automatically configure the required configuration for the spring boot application, such as if the data source bean in the classpath, if we using auto-configuration, it will automatically configure the JDBC template.

To disable the Auto-Configuration of spring boot, the developer needs to use can use those following commands in the main class or entry point of the application

@EnableAutoConfiguration(exclude={dataSourceAutoConfiguration.class})

If you want to exclude some class from auto-configuration

@EnableAutoConfiguration(excludeName={Sample.class})

We also exclude auto-configuration by declaring the following properties to a Properties file with a comma-separated class name

spring.autoconfigure.exclude= class1, class2, class3

What is @SpringBootApplication dose?

This annotation tells the spring boot that, use it that class as a bootstrap class or main class, it is a combination of @Configuration and @ComponentScan and @EnableAutoConfiguration annotation classes

Step of deploying the spring boot web application as JAR and WAR?

TO deploy the spring boot first we need to add spring-boot maven plugins as a dependency at pom.xml file

<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-dependency-plugin -->
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.1.1</version>
</dependency>

For Gradle Development

//https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-dependency-plugin
compile group: 'org.apache.maven.plugins', name: 'maven-dependency-plugin', version: '3.1.1'

Then set the packaging properties as JAR OR WAR at application.properties file

What is the best way to expose custom application configuration with spring boot?

One way to expose the custom application configuration is by using @Value annotation

but the only problem is that all configuration values will be distributed throughout the application, the developer can use a centralized approach, which means define configuration component by @ConfigurationPorperties annotation

@Component
@ConfigurationProperties(“example”)
public class SampleConfiguration {
private int number;
private boolean value;
private String message;
}

Then go to application.properties add the below:

example.number = 100
example.value= true
example.message= Dynamic Message

Mention the advantage of YML file then properties file and different way to load YAML file

In the YAML file data stored hierarchical format, so the developer can easily debug if any issue or error occurred. The spring application class support the YAML file as an alternative to properties whenever you use the snakeYAML library on your classpath

A different way to load YAML file to spring boot is

  1. YamlMapFactoryBean to load YAML as a MAP
  2. YamlMapPropertiesFactoryBean to load YAML as Properties

What do you understand by spring data REST?

Spring Data REST helps you to build the rest API easily and it provides the common abstraction to integrate with different kinds of data stores.

It helps to

  1. Expose the Rest server around spring data, without write a lot of code
  2. support SQL and Non_SQL based databases
  3. Support Pagination
  4. Enable filtering
  5. Allow sorting
  6. Support HATEOAS

TO build the simple project quickly with rest API

  1. Create the @Entity for application
  2. Then use @RepositoryRestResource
@RepositoryRestResource(collectionResourceRel= “todos”, path=“todos”)
public interface TotoRepository extend PaginationAndSortingRepository<Todo, Long> {
List<Todo> findByUser(@Param(“user”) string user)
}

What do path and collecitonResourceRel mean?

path: The section is used to mention the segment under which resource is to be exported

CollectionResourceRel The value is used to generate links to the collection resource

Explain how to register a custom auto-configuration?

To register an auto-configuration class

  1. first, need to mention the fully-qualified name the @EnableAutoConfiguratin key META-INF/spring factories file
  2. if will build with maven then the file should be placed in the resources/META-INF directory

How do you configure the Log4j for Logging?

Add the dependency to pom.xml file

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

In controller and service class we have implemented it by

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@RestController
class HelloController {
private static final Logger logger = LogManager.getLogger(HelloController.class);@GetMapping(“/“)
public String main(@PathVariable sting name) {
logger.debug(“My name is {}“, name)
return name;
}
}

Why Profiling is needed?

Profile used to provide a way to segregate the different parts of the application configuration and make it available for various environments.

It any @Component, @Configuration can be marked as @profile to limit the access in a different environment

If we have multiple environments Dev, QA, Stage, Production, So we can configure the specific component and configuration by using the @Profile annotation.

What are the steps to add the custom JS code with spring boot?

The steps are

  1. Create the folder and name it as static number resource folder
  2. In this folder, you can put the static content,

in case browser throws an unauthorized error, you need to give the permission access the file in SecurityConfiguration file

How to instruct and auto-configuration to back off when a bean exists?

We need to use @ConditionalOnMissingMean annotation

value : store the type of beans to be checked
name: name of the beans to be checked

Explain the Profiling with using scenario for specific configuration with spring boot

suppose we have 3 environment dev, test, production

We need to create three files

  1. application.properties for production
  2. application-dev.properties for dev
  3. application-test.properties for test

Add the same properties to all file with a different environment-specific value

Add properties to file applcation.properties

spring.profile.active = prod

Run the Spring application with

spring-boot:run -Dspring.profiles.active=prod

What is relaxation binding?

Relaxed binding, is a way in which, the property name does not need to match the key of the environment property. In Spring Boot, relaxed binding is applicable to the type-safe binding of the configuration properties. For example, if a property in a bean class with the @ConfigurationPropertie annotation is used sampleProp, then it can be bounded to any of the following environment properties:

  • sampleProp
  • sample-Prop
  • sample_Prop
  • SAMPLE_PROP

How to create the model or database persistence model in spring boot?

The developer needs to add @Entity and @Table annotation to create the persistence model in spring boot

import javax.persistence.Entity
import javax.persistence.Table
@Entity
@Table(name=“employees”)
public class Employee {
}

@Entity annotation with help to persist the database table with spring boot model or entity

@Table with can mapping the database table with entity

How to Applying the database query and action to the Spring application or how JpaRepository works?

A developer can use @Repository annotation so spring can understand that, it is a JPA repository and it has some action and operations to do with the database, And Extend the Repository class with @JpaRepository:

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {}

Then @Autowared the @Repository class to @Service Class to access the operations of Database

@Servicepublic class EmployeeService {@Autowired
EmployeeRepository repository;
public List<Employee> getAllEmployees() {List<Employee> employeeList = repository.findAll();if (emplouyeeList.size() >0){
return employeeList;
} else {
return new ArrayList<Employee>();
}
}
}

How to expose the API to a client in Spring Boot?

Using @RestController to expose the API to the client by spring boot

@RestController
@RestMapping(“/employee”)

public class EmployeeController {

@Autowired
EmployeeService employeeService;

@GetMapping
public ResponseEntity<List<Employee>> getAllEmployee() {

List<Employee> list = service.getAllEmployees();
return new ReponseEntity<List<Employee>>(list,
new HttpHeader(), HttpStatus.OK);
}
}

Is this possible to change the port of Embedded Tomcat server in Spring boot?

Yes, it’s possible to change the port.

You can use the application.properties file to change the port. But you need to mention “server.port(i.e. server.port=8081).

How do you Enable HTTP response compression in spring boot?

To enable HTTP response compression in spring boot using GZIP you have to add below settings in your application.properties file.

# Enabling HTTP response compression in spring boot
server.compression.enabled=true
server.compression.min-response-size=2048
server.compression.mime-types=application/json,application/xml,text/html,text/xml,text/plain

--

--

Tariqul Islam

Tariqul Islam have 9+ years of software development experience. He knows Python, Node Js and Java, C# , PHP.