Spring Boot Tutorials Point instant download
Spring Boot Tutorials Point instant download
https://ebookbell.com/product/spring-boot-tutorials-
point-46528248
https://ebookbell.com/product/spring-boot-persistence-best-practices-
optimize-java-persistence-performance-in-spring-boot-applications-1st-
edition-anghel-leonard-50194838
https://ebookbell.com/product/spring-boot-cookbook-alex-
antonov-55587912
https://ebookbell.com/product/spring-boot-3-recipes-a-problemsolution-
approach-for-java-microservices-and-cloudnative-applications-2nd-
marten-deinum-56416454
Spring Boot 30 Cookbook Proven Recipes For Building Modern And Robust
Java Web Applications With Spring Boot 1st Edition Felip Miguel Puig
https://ebookbell.com/product/spring-boot-30-cookbook-proven-recipes-
for-building-modern-and-robust-java-web-applications-with-spring-
boot-1st-edition-felip-miguel-puig-58534736
Spring Boot 20 Projects Build Productiongrade Reactive Applications
And Microservices With Spring Boot English Edition 1st Edition Mohamed
Shazin Sadakath
https://ebookbell.com/product/spring-boot-20-projects-build-
productiongrade-reactive-applications-and-microservices-with-spring-
boot-english-edition-1st-edition-mohamed-shazin-sadakath-22122616
https://ebookbell.com/product/spring-boot-up-and-running-mark-
heckler-33190044
Spring Boot With React And Aws Learn To Deploy A Full Stack Spring
Boot React Application To Aws 1st Edition Ravi Kant Soni
https://ebookbell.com/product/spring-boot-with-react-and-aws-learn-to-
deploy-a-full-stack-spring-boot-react-application-to-aws-1st-edition-
ravi-kant-soni-35072896
https://ebookbell.com/product/spring-boot-con-react-marco-
perez-36078380
https://ebookbell.com/product/spring-boot-in-practice-
meap-v09-meap-20211111-somnath-musib-36246368
Spring Boot In Action 1 Itebooks Craig Walls
https://ebookbell.com/product/spring-boot-in-action-1-itebooks-craig-
walls-5474486
Spring Boot
Spring Boot
Audience
This tutorial is designed for Java developers to understand and develop production-ready
spring applications with minimum configurations. It explores major features of Spring Boot
such as Starters, Auto-configuration, Beans, Actuator and more.
By the end of this tutorial, you will gain an intermediate level of expertise in Spring Boot.
Prerequisites
This tutorial is written for readers who have a prior experience of Java, Spring, Maven,
and Gradle. You can easily understand the concepts of Spring Boot if you have knowledge
on these concepts. It would be an additional advantage if you have an idea about writing
a RESTful Web Service. If you are a beginner, we suggest you to go through tutorials
related to these concepts before you start with Spring Boot.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at [email protected]
i
Spring Boot
Table of Contents
About the Tutorial ........................................................................................................................................... i
Audience .................................................................................................................................................... i
Prerequisites .............................................................................................................................................. i
Prerequisites ............................................................................................................................................. 6
Maven....................................................................................................................................................... 9
Gradle ..................................................................................................................................................... 10
ii
Spring Boot
iii
Spring Boot
Configure Logback................................................................................................................................... 38
iv
Spring Boot
GET ......................................................................................................................................................... 79
POST ....................................................................................................................................................... 80
PUT ......................................................................................................................................................... 81
DELETE .................................................................................................................................................... 82
v
Spring Boot
Maven................................................................................................................................................... 186
vi
Spring Boot
vii
Spring Boot
viii
1. Spring Boot – Introduction Spring Boot
Spring Boot is an open source Java-based framework used to create a micro Service. It is
developed by Pivotal Team and is used to build stand-alone and production ready spring
applications. This chapter will give you an introduction to Spring Boot and familiarizes you
with its basic concepts.
Advantages
Micro services offers the following advantages to its developers:
Easy deployment
Simple scalability
Compatible with Containers
Minimum configuration
Lesser production time
Advantages
Spring Boot offers the following advantages to its developers:
Goals
Spring Boot is designed with the following goals:
1
Spring Boot
It provides a flexible way to configure Java Beans, XML configurations, and Database
Transactions.
It provides a powerful batch processing and manages REST endpoints.
In Spring Boot, everything is auto configured; no manual configurations are needed.
It offers annotation-based spring application
Eases dependency management
It includes Embedded Servlet Container
The entry point of the spring boot application is the class contains
@SpringBootApplication annotation and the main method.
Spring Boot automatically scans all the components included in the project by using
@ComponentScan annotation.
For example, if you want to use Spring and JPA for database access, it is sufficient if you
include spring-boot-starter-data-jpa dependency in your project.
Note that all Spring Boot starters follow the same naming pattern spring-boot-starter-
*, where * indicates that it is a type of the application.
Examples
Look at the following Spring Boot starters explained below for a better understanding:
Spring Boot Starter Actuator dependency is used to monitor and manage your
application. Its code is shown below:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
2
Spring Boot
Spring Boot Starter Security dependency is used for Spring Security. Its code is shown
below:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Spring Boot Starter web dependency is used to write a Rest Endpoints. Its code is
shown below:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Spring Boot Starter Thyme Leaf dependency is used to create a web application. Its
code is shown below:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Spring Boot Starter Test dependency is used for writing Test cases. Its code is shown
below:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
Auto Configuration
Spring Boot Auto Configuration automatically configures your Spring application based on
the JAR dependencies you added in the project. For example, if MySQL database is on your
class path, but you have not configured any database connection, then Spring Boot auto-
configures an in-memory database.
3
Spring Boot
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@EnableAutoConfiguration
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
If you added @SpringBootApplication annotation to the class, you do not need to add
the @EnableAutoConfiguration, @ComponentScan and @SpringBootConfiguration
annotation. The @SpringBootApplication annotation includes all other annotations.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Component Scan
Spring Boot application scans all the beans and package declarations when the application
initializes. You need to add the @ComponentScan annotation for your class file to scan
your components added in your project.
import org.springframework.boot.SpringApplication;
4
Spring Boot
import org.springframework.context.annotation.ComponentScan;
@ComponentScan
public class DemoApplication {
5
2. Spring Boot – Quick Start Spring Boot
This chapter will teach you how to create a Spring Boot application using Maven and
Gradle.
Prerequisites
Your system need to have the following minimum requirements to create a Spring Boot
application:
Java 7
Maven 3.2
Gradle 2.5
This section explains you the steps involved in manual installation of Spring Boot CLI . For
further help, you can use the following link: https://docs.spring.io/spring-
boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-installing-spring-
boot
You can also download the Spring CLI distribution from the Spring Software repository at:
https://docs.spring.io/spring-boot/docs/current-
SNAPSHOT/reference/htmlsingle/#getting-started-manual-cli-installation
For manual installation, you need to use the following two folders:
spring-boot-cli-2.0.0.BUILD-SNAPSHOT-bin.zip
spring-boot-cli-2.0.0.BUILD-SNAPSHOT-bin.tar.gz
After the download, unpack the archive file and follow the steps given in the install.txt file.
Not that it does not require any environment setup.
In Windows, go to the Spring Boot CLI bin directory in the command prompt and run the
command spring –-version to make sure spring CLI is installed correctly. After executing
the command, you can see the spring CLI version as shown below:
6
Spring Boot
@Controller
class Example {
@RequestMapping("/")
@ResponseBody
public String hello() {
"Hello Spring Boot"
}
}
Now, save the groovy file with the name hello.groovy. Note that in this example, we
saved the groovy file inside the Spring Boot CLI bin directory. Now run the application by
using the command spring run hello.groovy as shown in the screenshot given below:
Once you run the groovy file, required dependencies will download automatically and it
will start the application in Tomcat 8080 port as shown in the screenshot given below:
Once Tomcat starts, go to the web browser and hit the URL http://localhost:8080/,
and you can see the output as shown.
7
3. Spring Boot – Bootstrapping Spring Boot
This chapter will explain you how to perform bootstrapping on a Spring Boot application.
Spring Initializer
One of the ways to Bootstrapping a Spring Boot application is by using Spring Initializer.
To do this, you will have to visit the Spring Initializer web page http://start.spring.io/ and
choose your Build, Spring Boot Version and platform. Also, you need to provide a Group,
Artifact and required dependencies to run the application.
Observe the following screenshot that shows an example where we added the spring-
boot-starter-web dependency to write REST Endpoints.
Once you provided the Group, Artifact, Dependencies, Build Project, Platform and Version,
click Generate Project button. The zip file will download and the files will be extracted.
This section explains you the examples by using both Maven and Gradle.
8
Spring Boot
Maven
After you download the project, unzip the file. Now, your pom.xml file looks as shown
below:
<groupId>com.tutorialspoint</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-
8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
9
Spring Boot
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Gradle
Once you download the project, unzip the file. Now your build.gradle file looks as shown
below:
buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-
plugin:${springBootVersion}")
}
}
apply plugin: 'java'
10
Spring Boot
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
Maven dependency
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
Gradle dependency
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
}
11
Spring Boot
Main Method
The main method should be writing the Spring Boot Application class. This class should be
annotated with @SpringBootApplication. This is the entry point of the spring boot
application to start. You can find the main class file under src/java/main directories with
the default package.
In this example, the main class file is located at the src/java/main directories with the
default package com.tutorialspoint.demo. Observe the code shown here for a better
understanding:
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
12
Spring Boot
@RequestMapping(value="/")
public String hello() {
return "Hello World";
}
}
After executing the command, you can see the BUILD SUCCESS message at the
command prompt as shown below:
13
Spring Boot
After executing the command, you can see the BUILD SUCCESSFUL message in the
command prompt as shown below:
For Maven, you can find the JAR file under the target directory as shown below:
14
Spring Boot
For Gradle, you can find the JAR file under the build/libs directory as shown below:
Now, run the JAR file by using the command java –jar <JARFILE>. Observe that in the
above example, the JAR file is named demo-0.0.1-SNAPSHOT.jar
Once you run the jar file, you can see the output in the console window as shown below:
Now, look at the console, Tomcat started on port 8080 (http). Now, go to the web browser
and hit the URL http://localhost:8080/ and you can see the output as shown below:
15
4. Spring Boot – Tomcat Deployment Spring Boot
By using Spring Boot application, we can create a war file to deploy into the web server.
In this chapter, you are going to learn how to create a WAR file and deploy the Spring
Boot application in Tomcat web server.
The code for Spring Boot Application class file for JAR file deployment is given below:
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
@SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder
application) {
return application.sources(DemoApplication.class);
16
Spring Boot
For Maven, add the start class in pom.xml properties as shown below:
<start-class>com.tutorialspoint.demo.DemoApplication</start-class>
For Gradle, add the main class name in build.gradle as shown below:
mainClassName="com.tutorialspoint.demo.DemoApplication"
<packaging>war</packaging>
For Gradle, add the application plugin and war plugin in the build.gradle as shown below:
Now, let us write a simple Rest Endpoint to return the string “Hello World from Tomcat”.
To write a Rest Endpoint, we need to add the Spring Boot web starter dependency into
our build file.
For Maven, add the Spring Boot starter dependency in pom.xml using the code as shown
below:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
17
Spring Boot
For Gradle, add the Spring Boot starter dependency in build.gradle using the code as
shown below:
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
}
Now, write a simple Rest Endpoint in Spring Boot Application class file using the code as
shown below:
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder
application) {
return application.sources(DemoApplication.class);
}
@RequestMapping(value="/")
public String hello() {
return "Hello World from Tomcat";
}
}
18
Spring Boot
For Maven, use the command mvn package for packaging your application. Then, the
WAR file will be created and you can find it in the target directory as shown in the
screenshots given below:
For Gradle, use the command gradle clean build for packaging your application. Then,
your WAR file will be created and you can find it under build/libs directory. Observe the
screenshots given here for a better understanding:
19
Spring Boot
20
Spring Boot
After successful deployment, hit the URL in your web browser http://localhost:8080/demo-
0.0.1-SNAPSHOT/ and observe that the output will look as shown in the screenshot given
below:
pom.xml
<groupId>com.tutorialspoint</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-
8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
21
Spring Boot
<start-class>com.tutorialspoint.demo.DemoApplication</start-class>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
build.gradle
buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
22
Spring Boot
classpath("org.springframework.boot:spring-boot-gradle-
plugin:${springBootVersion}")
}
}
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
mainClassName="com.tutorialspoint.demo.DemoApplication"
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
The code for main Spring Boot application class file is given below:
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication extends SpringBootServletInitializer {
23
Spring Boot
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder
application) {
return application.sources(DemoApplication.class);
}
@RequestMapping(value="/")
public String hello() {
return "Hello World from Tomcat";
}
}
24
5. Spring Boot – Build Systems Spring Boot
Dependency Management
Spring Boot team provides a list of dependencies to support the Spring Boot version for
its every release. You do not need to provide a version for dependencies in the build
configuration file. Spring Boot automatically configures the dependencies version based
on the release. Remember that when you upgrade the Spring Boot version, dependencies
also will upgrade automatically.
Note: If you want to specify the version for dependency, you can specify it in your
configuration file. However, the Spring Boot team highly recommends that it is not needed
to specify the version for dependency.
Maven Dependency
For Maven configuration, we should inherit the Spring Boot Starter parent project to
manage the Spring Boot Starters dependencies. For this, simply we can inherit the starter
parent in our pom.xml file as shown below.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
</parent>
We should specify the version number for Spring Boot Parent Starter dependency. Then
for other starter dependencies, we do not need to specify the Spring Boot version number.
Observe the code given below:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
25
Spring Boot
Gradle Dependency
We can import the Spring Boot Starters dependencies directly into build.gradle file. We
do not need Spring Boot start Parent dependency like Maven for Gradle. Observe the code
given below:
buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-
plugin:${springBootVersion}")
}
}
Similarly, in Gradle, we need not specify the Spring Boot version number for dependencies.
Spring Boot automatically configures the dependency based on the version.
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
}
26
6. Spring Boot – Code Structure Spring Boot
Spring Boot does not have any code layout to work with. However, there are some best
practices that will help us. This chapter talks about them in detail.
Default package
A class that does not have any package declaration is considered as a default package.
Note that generally a default package declaration is not recommended. Spring Boot will
cause issues such as malfunctioning of Auto Configuration or Component Scan, when you
use default package.
Note: Java’s recommended naming convention for package declaration is reversed domain
name. For example: com.tutorialspoint.myproject
Typical Layout
The typical layout of Spring Boot application is shown in the image given below:
The Application.java file should declare the main method along with
@SpringBootApplication. Observe the code given below for a better understanding:
package com.tutorialspoint.myproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args); }}
27
7. Spring Boot – Spring Beans and Dependency Spring Boot
Injection
In Spring Boot, we can use Spring Framework to define our beans and their dependency
injection. The @ComponentScan annotation is used to find beans and the corresponding
injected with @Autowired annotation.
If you followed the Spring Boot typical layout, no need to specify any arguments for
@ComponentScan annotation. All component class files are automatically registered with
Spring Beans.
The following example provides an idea about Auto wiring the Rest Template object and
creating a Bean for the same:
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
The following code shows the code for auto wired Rest Template object and Bean creation
object in main Spring Boot Application class file:
package com.tutorialspoint.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class DemoApplication {
@Autowired
RestTemplate restTemplate;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate(); }
}
28
8. Spring Boot – Runners Spring Boot
Application Runner and Command Line Runner interfaces lets you to execute the code
after the Spring Boot application is started. You can use these interfaces to perform any
actions immediately after the application has started. This chapter talks about them in
detail.
Application Runner
Application Runner is an interface used to execute the code after the Spring Boot
application started. The example given below shows how to implement the Application
Runner interface on the main class file.
package com.tutorialspoint.demo;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication implements ApplicationRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(ApplicationArguments arg0) throws Exception {
System.out.println("Hello World from Application Runner");
}
}
Now, if you observe the console window below Hello World from Application Runner,
the println statement is executed after the Tomcat started. Is the following screenshot
relevant?
29
Spring Boot
package com.tutorialspoint.demo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
Look at the console window below “Hello world from Command Line Runner” println
statement is executed after the Tomcat started.
30
9. Spring Boot – Application Properties Spring Boot
Step 1: After creating an executable JAR file, run it by using the command java –jar
<JARFILE>.
Step 2: Use the command given in the screenshot given below to change the port number
for Spring Boot application by using command line properties.
Note: You can provide more than one application properties by using the delimiter --.
Properties File
Properties files are used to keep ‘N’ number of properties in a single file to run the
application in a different environment. In Spring Boot, properties are kept in the
application.properties file under the classpath.
server.port=9090
spring.application.name=demoservice
Note that in the code shown above the Spring Boot application demoservice starts on the
port 9090.
YAML File
Spring Boot supports YAML based properties configurations to run the application. Instead
of application.properties, we can use application.yml file. This YAML file also should
be kept inside the classpath. The sample application.yml file is given below:
31
Spring Boot
spring:
application:
name: demoservice
server:
port: 9090
Externalized Properties
Instead of keeping the properties file under classpath, we can keep the properties in
different location or path. While running the JAR file, we can specify the properties file
path. You can use the following command to specify the location of properties file while
running the JAR:
-Dspring.config.location=C:\application.properties
@Value("${property_key_name}")
Look at the following example that shows the syntax to read the
spring.application.name property value in Java variable by using @Value annotation.
@Value("${spring.application.name}")
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
@Value("${spring.application.name}")
32
Spring Boot
@RequestMapping(value="/")
public String name() {
return name;
}
Note: If the property is not found while running the application, Spring Boot throws the
Illegal Argument exception as Could not resolve placeholder
'spring.application.name' in value "${spring.application.name}".
To resolve the placeholder issue, we can set the default value for the property using thr
syntax given below:
@Value("${property_key_name:default_value}")
@Value("${spring.application.name:demoservice}")
application.properties
server.port=8080
spring.application.name=demoservice
application-dev.properties
server.port=9090
spring.application.name=demoservice
33
Spring Boot
application-prod.properties
server.port=4431
spring.application.name=demoservice
While running the JAR file, we need to specify the spring active profile based on each
properties file. By default, Spring Boot application uses the application.properties file. The
command to set the spring active profile is shown below:
You can see active profile name on the console log as shown below:
Now, Tomcat has started on the port 9090 (http) as shown below:
You can see active profile name on the console log as shown below:
The following is an example code to keep the Spring active profiles in application.yml file.
Note that the delimiter (---) is used to separate each profile in application.yml file.
34
Spring Boot
spring:
application:
name: demoservice
server:
port: 8080
---
spring:
profiles: dev
application:
name: demoservice
server:
port: 9090
---
spring:
profiles: prod
application:
name: demoservice
server:
port: 4431
You can see active profile name on the console log as shown below:
35
Spring Boot
You can see active profile name on the console log as shown below:
This will start Tomcat on the port 4431 (http) as shown below:
36
10. Spring Boot – Logging Spring Boot
Spring Boot uses Apache Commons logging for all internal logging. Spring Boot’s default
configurations provides a support for the use of Java Util Logging, Log4j2, and Logback.
Using these, we can configure the console logging as well as file logging.
If you are using Spring Boot Starters, Logback will provide a good support for logging.
Besides, Logback also provides a use of good support for Common Logging, Util Logging,
Log4J, and SLF4J.
Log Format
The default Spring Boot Log format is shown in the screenshot given below.
Date and Time that gives the date and time of the log
Log level shows INFO, ERROR or WARN
Process ID
If you have to enable the debug level log, add the debug flag on starting your application
using the command shown below:
You can also add the debug mode to your application.properties file as shown here:
debug=true
37
Spring Boot
You can specify the log file path using the property shown below. Note that the log file
name is spring.log.
logging.path=/var/tmp/
You can specify the own log file name using the property shown below:
logging.file=/var/tmp/mylog.log
Note: Log files will rotate automatically after reaching the size 10 MB.
Log Levels
Spring Boot supports all logger levels such as “TRACE”, “DEBUG”, “INFO”, “WARN”,
“ERROR”, “FATAL”, “OFF”. You can define Root logger in the application.properties file as
shown below:
logging.level.root=WARN
Note: Logback does not support “FATAL” level log. It is mapped to the “ERROR” level log.
Configure Logback
Logback supports XML based configuration to handle Spring Boot Log configurations.
Logging configuration details are configured in logback.xml file. The logback.xml file
should be placed under the classpath.
You can configure the ROOT level log in Logback.xml file using the code given below:
You can configure the console appender in Logback.xml file given below.
You can configure the file appender in Logback.xml file using the code given below. Note
that you need to specify the Log file path insider the file appender.
38
Spring Boot
You can define the Log pattern in logback.xml file using the code given below. You can
also define the set of supported log patterns inside the console or file log appender using
the code given below:
The code for complete logback.xml file is given below. You have to place this in the class
path.
39
Spring Boot
The code given below shows how to add the slf4j logger in Spring Boot main class file.
package com.tutorialspoint.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
private static final Logger logger =
LoggerFactory.getLogger(DemoApplication.class);
public static void main(String[] args) {
logger.info("this is a info message");
logger.warn("this is a warn message");
logger.error("this is a error message");
SpringApplication.run(DemoApplication.class, args);
}
}
The output that you can see in the console window is shown here:
The output that you can see in the log file is shown here:
40
11. Spring Boot – Building RESTful Web Services Spring Boot
Spring Boot provides a very good support to building RESTful Web Services for enterprise
applications. This chapter will explain in detail about building RESTful web services using
Spring Boot.
Note: For building a RESTful Web Services, we need to add the Spring Boot Starter Web
dependency into the build configuration file.
If you are a Maven user, use the following code to add the below dependency in your
pom.xml file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
If you are a Gradle user, use the following code to add the below dependency in your
build.gradle file.
compile('org.springframework.boot:spring-boot-starter-web')
The code for complete build configuration file Maven build – pom.xml is given below:
41
Random documents with unrelated
content Scribd suggests to you:
The two Sioux watched the Pawnees until a bend in the 118
valley hid them from view. Angry Wolf started to crawl
away, but Little Eagle touched his arm to stop him. It
wasn’t long until a party of Pawnee warriors rode into
sight. Angry Wolf turned an admiring glance on Little
Eagle.
The warm sun had wiped away the frost and dried the 119
grass. For a while its heat made Little Eagle drowsy.
Now some clouds rolled up and hid the sun. The wind
was rising and it had a chilly edge. Little Eagle raised his
eyes to study the clouds. He saw that it wouldn’t be
long before rain started to fall.
“It was a high price to pay for one enemy,” Angry Wolf
agreed.
Little Eagle led the way across the valley to the trail by
which the Pawnees had fled from the Crows. He turned
down the trail in the direction the Pawnees had gone.
He rode across one stream but, at the second, left the
trail and rode to a thick grove of trees.
Before they went to sleep, the two boys ate some of the 124
cooked meat.
125
CHAPTER SIX
Little Eagle led the way. At first the route was up and
down wooded hills, but soon the hills became smaller
and the trees fewer. When they stopped to rest at
midday, Little Eagle could see the open prairie ahead of
them.
While Angry Wolf cooked meat for their meal, Little 129
Eagle made a pile of dry leaves for their bed. Both of
them were so tired that as soon as they had eaten they
put out the fire, crawled into the bed of leaves, and
pulled the deerskin over them.
The two boys made camp quickly. As soon as they had 131
a fire going, they built a shelter. It was dark by the time
they had the shelter finished. It was while they were
eating that the drops of rain began to change to flakes
of snow. In a short time the northwest wind was driving
the snow with stinging force.
Little Eagle sat down a few paces from the fire. He 138
wanted to think more about this problem. He tried to
imagine what advice Clawing Bear would give. When
the answer came, it was almost as if Clawing Bear were
speaking to him. He had the deer hide. It was powerful
medicine. He should take the hide and go away from
camp. If he rolled himself up in the deer hide and slept,
he might have a dream which would tell him what to do.
He told his thoughts to Angry Wolf.
“Get up, Little Eagle,” the voice said. “I’ll show you how 140
you can get horses from the Crows. They are my
enemies too.”
“Put it under that tree,” the bird said, nodding his head
toward a tree in the direction away from the camp. “My
family will use it to build warm nests for the winter
which is almost here.”
Little Eagle folded the skin neatly. The bird flew ahead 141
and perched on a limb while Little Eagle placed the hide
at the foot of the tree. The bird flew off to the west. He
went so quickly that Little Eagle didn’t have time to ask
for permission to get Angry Wolf. He had to run to keep
the bird in sight.
While it didn’t seem that they had traveled long, the sun
was down and darkness had fallen when they reached
the Crow camp. The camp had been set up on the
sheltered side of a grove of trees. The smell of roasting
buffalo meat made Little Eagle’s mouth water. A few
Crows were feasting on the fresh buffalo meat. Little
Eagle knew that most of the band had stuffed
themselves with fresh meat and had crawled into their
tepees to sleep.
The bird flew around the Crow camp, and Little Eagle
followed him. In a short time they came to the herd of
horses. Little Eagle saw the ones that belonged to Angry
Wolf and him. He guessed that the warrior who had
taken them had gone south until the storm stopped and
then had circled to join the Crows in this camp.
“See how easily you can take all the horses you want,” 142
the bird whispered.
Little Eagle looked around. What the bird said was true.
There were no guards. Most of the horses were out of
sight of the camp. Anyone who used reasonable care
could take horses from this herd.
“Then you are ready to accept the sign and try to get 144
horses from the Crows?” Little Eagle demanded.
“It was almost dark when the bird and I got there,”
Little Eagle answered. “We can go many paces before
darkness falls.”
They found a place where the sun had melted the snow 146
and dried the ground. Here they ate the cold meat they
had brought with them. For the first time since they had
started, Angry Wolf seemed to think they had a chance
to succeed.
“When we have horses again, we’ll hunt buffaloes,”
Angry Wolf said.
151
CHAPTER SEVEN
“You could hunt for fresh meat while I build a fire,” Little 155
Eagle suggested, hoping that by keeping Angry Wolf
busy, he could keep him in good spirits.
When Little Eagle awoke the next morning, he felt like 156
jumping and shouting. It seemed that he ought to
dance the Victory Dance. He and Angry Wolf had
escaped the Crows. The horses they had taken were
proof of a great victory. Because Angry Wolf was
already rounding up the horses, Little Eagle delayed his
celebration. He hurried to help the other boy.
“I’ll try to get a buffalo,” Angry Wolf said when they had
the horses driven together in a herd.
Before they started on, Little Eagle helped Angry Wolf 158
bring in the rest of the buffalo meat. They cut the
buffalo hide into two pieces. They placed the meat on
the pieces of hide, then wrapped the hide around the
meat so that each piece of hide made a big bundle.
They tied the two bundles on one of the horses. This
time Angry Wolf led the way, while Little Eagle rode
behind to keep the herd moving.
The prairie here was different from that they had been
crossing. The hills were higher and closer together. It
seemed to Little Eagle that they were always either
going up a hill or down one. He was glad that they
seemed to be safely away from the Crows. Here a party
of enemies might have ridden close before he or Angry
Wolf discovered them.
All morning they seldom saw a tree. They crossed a few 159
spring-fed streams, but even beside these there was
hardly ever a tree. Little Eagle and Angry Wolf
continually traded places so that part of the time Little
Eagle rode ahead and led the way, while at other times
he rode behind. About the middle of the afternoon he
was riding behind. The horses had given so little trouble
that he paid them scant attention. He was humming the
Victory Song under his breath when, for some reason,
he glanced back. A lone Crow warrior was charging
toward him!
Little Eagle didn’t know how long Angry Wolf was gone.
He felt himself falling. He braced himself with the hand
that held the horse’s mane and fought against the
darkness that was closing in on him. The wave of
darkness passed, and Little Eagle was still on his horse.
Angry Wolf looked at the arrow. His face was drawn and
he was gritting his teeth.
Little Eagle took a deep breath as Angry Wolf took hold 162
of the arrow. He felt a stab of hot pain as Angry Wolf
broke the arrow. In spite of himself, Little Eagle gasped
as Angry Wolf drew the rest of the arrow from the
wound. Little Eagle kept his head turned aside until he
was able to smile. When he looked toward his friend, he
saw that Angry Wolf’s face had the same sickly color it
had had when he had been wounded.
165
He added the powdered herbs and the bear’s grease
There was still daylight when Angry Wolf sighted trees 166
ahead. Before he reached the grove of trees, he saw
that they were growing along a stream. When he
reached the grove, he gently lifted Little Eagle to the
ground. He dug the bowl from one of the packs and
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
ebookbell.com