SpringBoot Notes
SpringBoot Notes
Advantages
Easy deployment
Simple scalability
Compatible with Containers
Minimum configuration
Lesser production time
Advantages
Goals
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
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<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.
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.EnableAutoConfig
uration;
@EnableAutoConfiguration
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,
args);
}
}
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
@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;
import
org.springframework.context.annotation.ComponentScan;
@ComponentScan
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,
args);
}
}
Prerequisites
Your system need to have the following minimum requirements to
create a Spring Boot application −
Java 7
Maven 3.2
Gradle 2.5
You can also download the Spring CLI distribution from the Spring
Software repository
at: https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/refe
rence/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.
@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 −
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 www.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.
This section explains you the examples by using both Maven and
Gradle.
Maven
After you download the project, unzip the file. Now,
your pom.xml file looks as shown below −
<modelVersion>4.0.0</modelVersion>
<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.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
</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>
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'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.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')
}
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.
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,
args);
}
}
Now, your main Spring Boot Application class file will look like as
shown in the code given below −
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
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 −
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.SpringBootApplic
ation;
@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.SpringBootApplic
ation;
import
org.springframework.boot.builder.SpringApplicationBuild
er;
import
org.springframework.boot.web.servlet.support.SpringBoot
ServletInitializer;
@SpringBootApplication
public class DemoApplication extends
SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder
configure(SpringApplicationBuilder application) {
return
application.sources(DemoApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,
args);
}
}
<start-class>com.tutorialspoint.demo.DemoApplication</start-class>
mainClassName="com.tutorialspoint.demo.DemoApplication"
<packaging>war</packaging>
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
}
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import
org.springframework.boot.builder.SpringApplicationBuild
er;
import
org.springframework.boot.web.servlet.support.SpringBoot
ServletInitializer;
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);
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,
args);
}
@RequestMapping(value = "/")
public String hello() {
return "Hello World from Tomcat";
}
}
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 −
Deploy into Tomcat
Now, run the Tomcat Server, and deploy the WAR file under
the webapps directory. Observe the screenshots shown here for
a better understanding −
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 −
xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<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.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
<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 {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
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.SpringBootApplic
ation;
import
org.springframework.boot.builder.SpringApplicationBuild
er;
import
org.springframework.boot.web.servlet.support.SpringBoot
ServletInitializer;
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);
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,
args);
}
@RequestMapping(value = "/")
public String hello() {
return "Hello World from Tomcat";
}
}
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.
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>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
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')
}
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.
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.SpringBootApplic
ation;
@SpringBootApplication
public class Application {
public static void main(String[] args)
{SpringApplication.run(Application.class, args);}
}
@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.SpringBootApplic
ation;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class DemoApplication {
@Autowired
RestTemplate restTemplate;
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.SpringBootApplic
ation;
@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?
Command Line Runner
Command Line Runner is an interface. It is used to execute the
code after the Spring Boot application started. The example given
below shows how to implement the Command Line Runner
interface on the main class file.
package com.tutorialspoint.demo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
@SpringBootApplication
public class DemoApplication implements
CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,
args);
}
@Override
public void run(String... arg0) throws Exception {
System.out.println("Hello world from Command Line
Runner");
}
}
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 −
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}")
@Value("${spring.application.name}")
import
org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
@Value("${spring.application.name}")
private String name;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,
args);
}
@RequestMapping(value = "/")
public String name() {
return 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
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 −
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 −
You can see active profile name on the console log as shown
below −
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
The --- which is a separator
Thread name is enclosed within the square brackets []
Logger Name that shows the Source class name
The Log message
debug = true
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
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
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 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.
The code for complete logback.xml file is given below. You have
to place this in the class path.
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.SpringBootApplic
ation;
@SpringBootApplication
public class DemoApplication {
private static final Logger logger =
LoggerFactory.getLogger(DemoApplication.class);
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 −
<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')
<modelVersion>4.0.0</modelVersion>
<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/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
</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>
buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
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')
}
Rest Controller
The @RestController annotation is used to define the RESTful web
services. It serves JSON, XML and custom response. Its syntax is
shown below −
@RestController
public class ProductServiceController {
}
Request Mapping
The @RequestMapping annotation is used to define the Request
URI to access the REST Endpoints. We can define Request method
to consume and produce object. The default request method is
GET.
@RequestMapping(value = "/products")
public ResponseEntity<Object> getProducts() { }
Request Body
The @RequestBody annotation is used to define the request body
content type.
Path Variable
The @PathVariable annotation is used to define the custom or
dynamic request URI. The Path variable in request URI is defined
as curly braces {} as shown below −
Request Parameter
The @RequestParam annotation is used to read the request
parameters from the Request URL. By default, it is a required
parameter. We can also set default value for request parameters
as shown here −
GET API
The default HTTP request method is GET. This method does not
require any Request Body. You can send request parameters and
path variables to define the custom or dynamic URL.
The sample code to define the HTTP GET request method is
shown below. In this example, we used HashMap to store the
Product. Note that we used a POJO class as the product to be
stored.
Here, the request URI is /products and it will return the list of
products from HashMap repository. The controller class file is
given below that contains GET method REST Endpoint.
package com.tutorialspoint.demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RestController;
import com.tutorialspoint.demo.model.Product;
@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo =
new HashMap<>();
static {
Product honey = new Product();
honey.setId("1");
honey.setName("Honey");
productRepo.put(honey.getId(), honey);
The following example shows the sample code to define the HTTP
POST request method. In this example, we used HashMap to store
the Product, where the product is a POJO class.
Here, the request URI is /products, and it will return the String
after storing the product into HashMap repository.
package com.tutorialspoint.demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import
org.springframework.web.bind.annotation.RequestBody;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RequestMethod;
import
org.springframework.web.bind.annotation.RestController;
import com.tutorialspoint.demo.model.Product;
@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo =
new HashMap<>();
PUT API
The HTTP PUT request is used to update the existing resource.
This method contains a Request Body. We can send request
parameters and path variables to define the custom or dynamic
URL.
The example given below shows how to define the HTTP PUT
request method. In this example, we used HashMap to update the
existing Product, where the product is a POJO class.
package com.tutorialspoint.demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import
org.springframework.web.bind.annotation.PathVariable;
import
org.springframework.web.bind.annotation.RequestBody;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RequestMethod;
import
org.springframework.web.bind.annotation.RestController;
import com.tutorialspoint.demo.model.Product;
@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo =
new HashMap<>();
@RequestMapping(value = "/products/{id}", method =
RequestMethod.PUT)
public ResponseEntity<Object>
updateProduct(@PathVariable("id") String id,
@RequestBody Product product) {
productRepo.remove(id);
product.setId(id);
productRepo.put(id, product);
return new ResponseEntity<>("Product is updated
successsfully", HttpStatus.OK);
}
}
DELETE API
The HTTP Delete request is used to delete the existing resource.
This method does not contain any Request Body. We can send
request parameters and path variables to define the custom or
dynamic URL.
The example given below shows how to define the HTTP DELETE
request method. In this example, we used HashMap to remove
the existing product, which is a POJO class.
package com.tutorialspoint.demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import
org.springframework.web.bind.annotation.PathVariable;
import
org.springframework.web.bind.annotation.RequestBody;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RequestMethod;
import
org.springframework.web.bind.annotation.RestController;
import com.tutorialspoint.demo.model.Product;
@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo =
new HashMap<>();
This section gives you the complete set of source code. Observe
the following codes for their respective functionalities −
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,
args);
}
}
package com.tutorialspoint.demo.model;
package com.tutorialspoint.demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import
org.springframework.web.bind.annotation.PathVariable;
import
org.springframework.web.bind.annotation.RequestBody;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RequestMethod;
import
org.springframework.web.bind.annotation.RestController;
import com.tutorialspoint.demo.model.Product;
@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo =
new HashMap<>();
static {
Product honey = new Product();
honey.setId("1");
honey.setName("Honey");
productRepo.put(honey.getId(), honey);
@RequestMapping(value = "/products")
public ResponseEntity<Object> getProduct() {
return new ResponseEntity<>(productRepo.values(),
HttpStatus.OK);
}
}
You can create an executable JAR file, and run the spring boot
application by using the below Maven or Gradle commands as
shown −
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
You can run the JAR file by using the command shown below −
This will start the application on the Tomcat port 8080 as shown
below −
Now hit the URL shown below in POSTMAN application and see the
output.
Controller Advice
The @ControllerAdvice is an annotation, to handle the exceptions
globally.
Exception Handler
The @ExceptionHandler is an annotation used to handle the
specific exceptions and sending the custom responses to the
client.
package com.tutorialspoint.demo.exception;
import
org.springframework.web.bind.annotation.ControllerAdvic
e;
@ControllerAdvice
public class ProductExceptionController {
}
package com.tutorialspoint.demo.exception;
@ExceptionHandler(value =
ProductNotfoundException.class)
public ResponseEntity<Object>
exception(ProductNotfoundException exception) {
}
Now, use the code given below to throw the exception from the
API.
package com.tutorialspoint.demo.exception;
public class ProductNotfoundException extends
RuntimeException {
private static final long serialVersionUID = 1L;
}
package com.tutorialspoint.demo.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import
org.springframework.web.bind.annotation.ControllerAdvic
e;
import
org.springframework.web.bind.annotation.ExceptionHandle
r;
@ControllerAdvice
public class ProductExceptionController {
@ExceptionHandler(value =
ProductNotfoundException.class)
public ResponseEntity<Object>
exception(ProductNotfoundException exception) {
return new ResponseEntity<>("Product not found",
HttpStatus.NOT_FOUND);
}
}
package com.tutorialspoint.demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import
org.springframework.web.bind.annotation.PathVariable;
import
org.springframework.web.bind.annotation.RequestBody;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RequestMethod;
import
org.springframework.web.bind.annotation.RestController;
import
com.tutorialspoint.demo.exception.ProductNotfoundExcept
ion;
import com.tutorialspoint.demo.model.Product;
@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo =
new HashMap<>();
static {
Product honey = new Product();
honey.setId("1");
honey.setName("Honey");
productRepo.put(honey.getId(), honey);
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.SpringBootApplic
ation;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,
args);
}
}
The code for POJO class for Product is given below −
package com.tutorialspoint.demo.model;
public class Product {
private String id;
private String name;
<modelVersion>4.0.0</modelVersion>
<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/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
</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>
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')
}
You can create an executable JAR file, and run the Spring Boot
application by using the Maven or Gradle commands −
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
You can run the JAR file by using the following command −
This will start the application on the Tomcat port 8080 as shown
below −
Now hit the below URL in POSTMAN application and you can see
the output as shown below −
The following are the three methods you should know about while
working on Interceptors −
@Component
public class ProductServiceInterceptor implements
HandlerInterceptor {
@Override
public boolean preHandle(
HttpServletRequest request, HttpServletResponse
response, Object handler) throws Exception {
return true;
}
@Override
public void postHandle(
HttpServletRequest request, HttpServletResponse
response, Object handler,
ModelAndView modelAndView) throws Exception {}
@Override
public void afterCompletion(HttpServletRequest
request, HttpServletResponse response,
Object handler, Exception exception) throws
Exception {}
}
@Override
public void addInterceptors(InterceptorRegistry
registry) {
registry.addInterceptor(productServiceInterceptor);
}
}
In the example given below, we are going to hit the GET products
API which gives the output as given under −
package com.tutorialspoint.demo.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import
org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Component
public class ProductServiceInterceptor implements
HandlerInterceptor {
@Override
public boolean preHandle
(HttpServletRequest request, HttpServletResponse
response, Object handler)
throws Exception {
package com.tutorialspoint.demo.interceptor;
import
org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import
org.springframework.web.servlet.config.annotation.Inter
ceptorRegistry;
import
org.springframework.web.servlet.config.annotation.WebMv
cConfigurerAdapter;
@Component
public class ProductServiceInterceptorAppConfig extends
WebMvcConfigurerAdapter {
@Autowired
ProductServiceInterceptor productServiceInterceptor;
@Override
public void addInterceptors(InterceptorRegistry
registry) {
registry.addInterceptor(productServiceInterceptor);
}
}
package com.tutorialspoint.demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import
org.springframework.web.bind.annotation.PathVariable;
import
org.springframework.web.bind.annotation.RequestBody;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RequestMethod;
import
org.springframework.web.bind.annotation.RestController;
import
com.tutorialspoint.demo.exception.ProductNotfoundExcept
ion;
import com.tutorialspoint.demo.model.Product;
@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo =
new HashMap<>();
static {
Product honey = new Product();
honey.setId("1");
honey.setName("Honey");
productRepo.put(honey.getId(), honey);
Product almond = new Product();
almond.setId("2");
almond.setName("Almond");
productRepo.put(almond.getId(), almond);
}
@RequestMapping(value = "/products")
public ResponseEntity<Object> getProduct() {
return new ResponseEntity<>(productRepo.values(),
HttpStatus.OK);
}
}
package com.tutorialspoint.demo.model;
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,
args);
}
}
<modelVersion>4.0.0</modelVersion>
<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/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
</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>
buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.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')
}
You can create an executable JAR file, and run the Spring Boot
application by using the below Maven or Gradle commands.
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
You can run the JAR file by using the following command −
Now hit the below URL in POSTMAN application and you can see
the output as shown under −
The following code shows the sample code for a Servlet Filter
implementation class with @Component annotation.
@Component
public class SimpleFilter implements Filter {
@Override
public void destroy() {}
@Override
public void doFilter
(ServletRequest request, ServletResponse
response, FilterChain filterchain)
throws IOException, ServletException {}
@Override
public void init(FilterConfig filterconfig) throws
ServletException {}
}
The following example shows the code for reading the remote
host and remote address from the ServletRequest object before
sending the request to the controller.
package com.tutorialspoint.demo;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.springframework.stereotype.Component;
@Component
public class SimpleFilter implements Filter {
@Override
public void destroy() {}
@Override
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain filterchain)
throws IOException, ServletException {
System.out.println("Remote
Host:"+request.getRemoteHost());
System.out.println("Remote
Address:"+request.getRemoteAddr());
filterchain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterconfig) throws
ServletException {}
}
In the Spring Boot main application class file, we have added the
simple REST endpoint that returns the “Hello World” string.
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,
args);
}
@RequestMapping(value = "/")
public String hello() {
return "Hello World";
}
}
<modelVersion>4.0.0</modelVersion>
<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/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
</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>
buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
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')
}
You can create an executable JAR file, and run the Spring Boot
application by using the Maven or Gradle commands shown below
−
After BUILD SUCCESS, you can find the JAR file under the target
directory.
After BUILD SUCCESSFUL, you can find the JAR file under the
build/libs directory.
You can see the application has started on the Tomcat port 8080.
Now hit the URL http://localhost:8080/ and see the output Hello
World. It should look as shown below −
Then, you can see the Remote host and Remote address on the
console log as shown below −
Custom Port
In the application.properties file, we can set custom port
number for the property server.port
server.port = 9090
server:
port: 9090
Random Port
In the application.properties file, we can set random port
number for the property server.port
server.port = 0
In the application.yml file, you can find as follows −
server:
port: 0
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,
args);
}
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
GET
Consuming the GET API by using RestTemplate -
exchange() method
Assume this URL http://localhost:8080/products returns the
following JSON and we are going to consume this API response by
using Rest Template using the following code −
[
{
"id": "1",
"name": "Honey"
},
{
"id": "2",
"name": "Almond"
}
]
You will have to follow the given points to consume the API −
@RequestMapping(value = "/template/products")
public String getProductList() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_J
SON));
HttpEntity <String> entity = new
HttpEntity<String>(headers);
return restTemplate.exchange("
http://localhost:8080/products",
HttpMethod.GET, entity, String.class).getBody();
}
}
POST
Consuming POST API by using RestTemplate - exchange()
method
{
"id":"3",
"name":"Ginger"
}
You will have to follow the points given below to consume the API
−
headers.setAccept(Arrays.asList(MediaType.APPLICATION_J
SON));
HttpEntity<Product> entity = new
HttpEntity<Product>(product,headers);
return restTemplate.exchange(
"http://localhost:8080/products",
HttpMethod.POST, entity, String.class).getBody();
}
}
PUT
Consuming PUT API by using RestTemplate - exchange()
method
{
"name":"Indian Ginger"
}
You will have to follow the points given below to consume the API
−
@RequestMapping(value = "/template/products/{id}",
method = RequestMethod.PUT)
public String updateProduct(@PathVariable("id")
String id, @RequestBody Product product) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_J
SON));
HttpEntity<Product> entity = new
HttpEntity<Product>(product,headers);
return restTemplate.exchange(
"http://localhost:8080/products/"+id,
HttpMethod.PUT, entity, String.class).getBody();
}
}
DELETE
Consuming DELETE API by using RestTemplate -
exchange() method
You will have to follow the points shown below to consume the API
−
@RequestMapping(value = "/template/products/{id}",
method = RequestMethod.DELETE)
public String deleteProduct(@PathVariable("id")
String id) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_J
SON));
HttpEntity<Product> entity = new
HttpEntity<Product>(headers);
return restTemplate.exchange(
"http://localhost:8080/products/"+id,
HttpMethod.DELETE, entity, String.class).getBody();
}
}
package com.tutorialspoint.demo.controller;
import java.util.Arrays;
import
org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import
org.springframework.web.bind.annotation.PathVariable;
import
org.springframework.web.bind.annotation.RequestBody;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RequestMethod;
import
org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.tutorialspoint.demo.model.Product;
@RestController
public class ConsumeWebService {
@Autowired
RestTemplate restTemplate;
@RequestMapping(value = "/template/products")
public String getProductList() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_J
SON));
HttpEntity<String> entity = new
HttpEntity<String>(headers);
return restTemplate.exchange(
"http://localhost:8080/products",
HttpMethod.GET, entity, String.class).getBody();
}
@RequestMapping(value = "/template/products", method
= RequestMethod.POST)
public String createProducts(@RequestBody Product
product) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_J
SON));
HttpEntity<Product> entity = new
HttpEntity<Product>(product,headers);
return restTemplate.exchange(
"http://localhost:8080/products",
HttpMethod.POST, entity, String.class).getBody();
}
@RequestMapping(value = "/template/products/{id}",
method = RequestMethod.PUT)
public String updateProduct(@PathVariable("id")
String id, @RequestBody Product product) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_J
SON));
HttpEntity<Product> entity = new
HttpEntity<Product>(product,headers);
return restTemplate.exchange(
"http://localhost:8080/products/"+id,
HttpMethod.PUT, entity, String.class).getBody();
}
@RequestMapping(value = "/template/products/{id}",
method = RequestMethod.DELETE)
public String deleteProduct(@PathVariable("id")
String id) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_J
SON));
HttpEntity<Product> entity = new
HttpEntity<Product>(headers);
return restTemplate.exchange(
"http://localhost:8080/products/"+id,
HttpMethod.DELETE, entity, String.class).getBody();
}
}
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,
args);
}
}
<modelVersion>4.0.0</modelVersion>
<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/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
</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>
buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-
starter-web')
testCompile('org.springframework.boot:spring-boot-
starter-test')
}
You can create an executable JAR file, and run the Spring Boot
application by using the following Maven or Gradle commands −
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
After “BUILD SUCCESSFUL”, you can find the JAR file under
build/libs directory.
Now hit the below URL’s in POSTMAN application and you can see
the output.
GET Products by Rest Template
− http://localhost:8080/template/products
File Upload
For uploading a file, you can use MultipartFile as a Request
Parameter and this API should consume Multi-Part form data
value. Observe the code given below −
@RequestMapping(value = "/upload", method =
RequestMethod.POST, consumes =
MediaType.MULTIPART_FORM_DATA_VALUE)
package com.tutorialspoint.demo.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.springframework.http.MediaType;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RequestMethod;
import
org.springframework.web.bind.annotation.RequestParam;
import
org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class FileUploadController {
@RequestMapping(value = "/upload", method =
RequestMethod.POST,
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
File Download
For file download, you should use InputStreamResource for
downloading a File. We need to set the HttpHeader Content-
Disposition in Response and need to specify the response Media
Type of the application.
headers.add("Content-Disposition",
String.format("attachment; filename=\"%s\"",
file.getName()));
headers.add("Cache-Control", "no-cache, no-store,
must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
ResponseEntity<Object>
responseEntity =
ResponseEntity.ok().headers(headers).contentLength(file
.length()).contentType(
MediaType.parseMediaType("application/txt")).body(resou
rce);
return responseEntity;
}
package com.tutorialspoint.demo.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RequestMethod;
import
org.springframework.web.bind.annotation.RestController;
@RestController
public class FileDownloadController {
@RequestMapping(value = "/download", method =
RequestMethod.GET)
public ResponseEntity<Object> downloadFile() throws
IOException {
String filename = "/var/tmp/mysql.png";
File file = new File(filename);
InputStreamResource resource = new
InputStreamResource(new FileInputStream(file));
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition",
String.format("attachment; filename=\"%s\"",
file.getName()));
headers.add("Cache-Control", "no-cache, no-store,
must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
ResponseEntity<Object>
responseEntity =
ResponseEntity.ok().headers(headers).contentLength(
file.length()).contentType(MediaType.parseMediaType("ap
plication/txt")).body(resource);
return responseEntity;
}
}
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,
args);
}
}
<modelVersion>4.0.0</modelVersion>
<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/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
</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>
buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
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')
}
Now you can create an executable JAR file, and run the Spring
Boot application by using the Maven or Gradle commands given
below −
For Maven, use the command given below −
After “BUILD SUCCESS”, you can find the JAR file under target
directory.
After “BUILD SUCCESSFUL”, you can find the JAR file under
build/libs directory.
This will start the application on the Tomcat port 8080 as shown
below −
Now hit the below URL’s in POSTMAN application and you can see
the output as shown below −
@Service
public class ProductServiceImpl implements
ProductService {
}
You can create an Interface which contains add, edit, get and
delete methods using the code as shown below −
package com.tutorialspoint.demo.service;
import java.util.Collection;
import com.tutorialspoint.demo.model.Product;
The following code will let you to create a class which implements
the ProductService interface with @Service annotation and write
the business logic to store, retrieve, delete and updates the
product.
package com.tutorialspoint.demo.service;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.tutorialspoint.demo.model.Product;
@Service
public class ProductServiceImpl implements
ProductService {
private static Map<String, Product> productRepo =
new HashMap<>();
static {
Product honey = new Product();
honey.setId("1");
honey.setName("Honey");
productRepo.put(honey.getId(), honey);
}
@Override
public Collection<Product> getProducts() {
return productRepo.values();
}
}
The code here show the Rest Controller class file, here we
@Autowired the ProductService interface and called the methods.
package com.tutorialspoint.demo.controller;
import
org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import
org.springframework.web.bind.annotation.PathVariable;
import
org.springframework.web.bind.annotation.RequestBody;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RequestMethod;
import
org.springframework.web.bind.annotation.RestController;
import com.tutorialspoint.demo.model.Product;
import com.tutorialspoint.demo.service.ProductService;
@RestController
public class ProductServiceController {
@Autowired
ProductService productService;
@RequestMapping(value = "/products")
public ResponseEntity<Object> getProduct() {
return new
ResponseEntity<>(productService.getProducts(),
HttpStatus.OK);
}
@RequestMapping(value = "/products/{id}", method =
RequestMethod.PUT)
public ResponseEntity<Object>
updateProduct(@PathVariable("id") String id,
@RequestBody Product product) {
productService.updateProduct(id, product);
return new ResponseEntity<>("Product is updated
successsfully", HttpStatus.OK);
}
@RequestMapping(value = "/products/{id}", method =
RequestMethod.DELETE)
public ResponseEntity<Object>
delete(@PathVariable("id") String id) {
productService.deleteProduct(id);
return new ResponseEntity<>("Product is deleted
successsfully", HttpStatus.OK);
}
@RequestMapping(value = "/products", method =
RequestMethod.POST)
public ResponseEntity<Object>
createProduct(@RequestBody Product product) {
productService.createProduct(product);
return new ResponseEntity<>("Product is created
successfully", HttpStatus.CREATED);
}
}
package com.tutorialspoint.demo.model;
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,
args);
}
}
<modelVersion>4.0.0</modelVersion>
<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/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
</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>
buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
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')
}
You can create an executable JAR file, and run the Spring Boot
application by using the Maven or Gradle commands given below
−
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
After “BUILD SUCCESSFUL”, you can find the JAR file under
build/libs directory.
Now hit the below URL’s in POSTMAN application and you can see
the output as shown below −
Thymeleaf Templates
Thymeleaf converts your files into well-formed XML files. It
contains 6 types of templates as given below −
XML
Valid XML
XHTML
Valid XHTML
HTML5
Legacy HTML5
Web Application
You can use Thymeleaf templates to create a web application in
Spring Boot. You will have to follow the below steps to create a
web application in Spring Boot by using Thymeleaf.
package com.tutorialspoint.demo.controller;
import org.springframework.stereotype.Controller;
import
org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class WebController {
@RequestMapping(value = "/index")
public String index() {
return "index";
}
}
In the above example, the request URI is /index, and the control
is redirected into the index.html file. Note that the index.html file
should be placed under the templates directory and all JS and CSS
files should be placed under the static directory in classpath. In
the example shown, we used CSS file to change the color of the
text.
You can use the following code and created a CSS file in separate
folder css and name the file as styles.css −
h4 {
color: red;
}
<!DOCTYPE html>
<html>
<head>
<meta charset = "ISO-8859-1" />
<link href = "css/styles.css" rel =
"stylesheet"/>
<title>Spring Boot Application</title>
</head>
<body>
<h4>Welcome to Thymeleaf Spring Boot web
application</h4>
</body>
</html>
Maven users can add the following dependency into the pom.xml
file −
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
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.SpringBootApplic
ation;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,
args);
}
}
<modelVersion>4.0.0</modelVersion>
<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 />
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
</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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-
starter-web')
compile group: 'org.springframework.boot', name:
'spring-boot-starter-thymeleaf'
testCompile('org.springframework.boot:spring-boot-
starter-test')
}
You can create an executable JAR file, and run the spring boot
application by using the following Maven or Gradle commands −
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
Now hit the URL in your web browser and you can see the output
as shown −
http://localhost:8080/index
Consuming RESTful Web
Services
This chapter will discuss in detail about consuming a RESTful Web
Services by using jQuery AJAX.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
@Controller
public class ViewController {
}
You can define the Request URI methods to redirects into the
HTML file as shown below −
@RequestMapping(“/view-products”)
public String viewProducts() {
return “view-products”;
}
@RequestMapping(“/add-products”)
public String addProducts() {
return “add-products”;
}
[
{
"id": "1",
"name": "Honey"
},
{
"id": "2",
"name": "Almond"
}
]
In the HTML file, we added the jQuery library and written the code
to consume the RESTful web service on page load.
<script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jqu
ery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON("http://localhost:9090/products",
function(result){
$.each(result, function(key,value) {
$("#productsJson").append(value.id+"
"+value.name+" ");
});
});
});
</script>
{
"id":"3",
"name":"Ginger"
}
In the HTML file, we added the jQuery library and written the code
that submits the form to RESTful web service on clicking the
button.
<script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jqu
ery.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
var productmodel = {
id : "3",
name : "Ginger"
};
var requestJSON =
JSON.stringify(productmodel);
$.ajax({
type : "POST",
url : "http://localhost:9090/products",
headers : {
"Content-Type" : "application/json"
},
data : requestJSON,
success : function(data) {
alert(data);
},
error : function(data) {
}
});
});
});
</script>
<modelVersion>4.0.0</modelVersion>
<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 />
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
</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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
buildscript {
ext {
springBootVersion = ‘1.5.8.RELEASE’
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
group = ‘com.tutorialspoint’
version = ‘0.0.1-SNAPSHOT’
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile(‘org.springframework.boot:spring-boot-
starter-web’)
compile group: ‘org.springframework.boot’, name:
‘spring-boot-starter-thymeleaf’
testCompile(‘org.springframework.boot:spring-boot-
starter-test’)
}
package com.tutorialspoint.demo.controller;
import org.springframework.stereotype.Controller;
import
org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ViewController {
@RequestMapping(“/view-products”)
public String viewProducts() {
return “view-products”;
}
@RequestMapping(“/add-products”)
public String addProducts() {
return “add-products”;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset = "ISO-8859-1"/>
<title>View Products</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jqu
ery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON("http://localhost:9090/products",
function(result){
$.each(result, function(key,value) {
$("#productsJson").append(value.id+"
"+value.name+" ");
});
});
});
</script>
</head>
<body>
<div id = "productsJson"> </div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset = "ISO-8859-1" />
<title>Add Products</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jqu
ery.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
var productmodel = {
id : "3",
name : "Ginger"
};
var requestJSON =
JSON.stringify(productmodel);
$.ajax({
type : "POST",
url :
"http://localhost:9090/products",
headers : {
"Content-Type" :
"application/json"
},
data : requestJSON,
success : function(data) {
alert(data);
},
error : function(data) {
}
});
});
});
</script>
</head>
<body>
<button>Click here to submit the form</button>
</body>
</html>
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,
args);
}
}
Now, you can create an executable JAR file, and run the Spring
Boot application by using the following Maven or Gradle
commands.
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
Now hit the URL in your web browser and you can see the output
as shown −
http://localhost:8080/view-products
http://localhost:8080/add-products
Now, click the button Click here to submit the form and you
can see the result as shown −
Now, hit the view products URL and see the created product.
http://localhost:8080/view-products
Angular JS
To consume the APIs by using Angular JS, you can use the
examples given below −
angular.module('demo', [])
.controller('Hello', function($scope, $http) {
$http.get('http://localhost:9090/products').
then(function(response) {
$scope.products = response.data;
});
});
Use the following code to create the Angular JS Controller to
consume the POST API - http://localhost:9090/products −
angular.module('demo', [])
.controller('Hello', function($scope, $http) {
$http.post('http://localhost:9090/products',data).
then(function(response) {
console.log("Product created successfully");
});
});
@RequestMapping(value = "/products")
@CrossOrigin(origins = "http://localhost:8080")
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry
registry) {
registry.addMapping("/products").allowedOrigins("http:/
/localhost:9000");
}
};
}
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import org.springframework.context.annotation.Bean;
import
org.springframework.web.servlet.config.annotation.CorsR
egistry;
import
org.springframework.web.servlet.config.annotation.WebMv
cConfigurer;
import
org.springframework.web.servlet.config.annotation.WebMv
cConfigurerAdapter;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,
args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry
registry) {
registry.addMapping("/products").allowedOrigins("http:/
/localhost:8080");
}
};
}
}
Now, you can create a Spring Boot web application that runs on
8080 port and your RESTful web service application that can run
on the 9090 port. For further details about implementation about
RESTful Web Service, you can refer to the chapter
titled Consuming RESTful Web Services of this tutorial.
Spring Boot -
Internationalization
Internationalization is a process that makes your application
adaptable to different languages and regions without engineering
changes on the source code. In ither words, Internationalization is
a readiness of Localization.
Dependencies
We need the Spring Boot Starter Web and Spring Boot Starter
Thymeleaf dependency to develop a web application in Spring
Boot.
Maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Gradle
compile('org.springframework.boot:spring-boot-starter-web')
compile group: 'org.springframework.boot', name: 'spring-boot-starter-
thymeleaf'
LocaleResolver
We need to determine default Locale of your application. We need
to add the LocaleResolver bean in our Spring Boot application.
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver sessionLocaleResolver = new
SessionLocaleResolver();
sessionLocaleResolver.setDefaultLocale(Locale.US);
return sessionLocaleResolver;
}
LocaleChangeInterceptor
LocaleChangeInterceptor is a used to change the new Locale
based on the value of the language parameter added to a
request.
@Bean
public LocaleChangeInterceptor
localeChangeInterceptor() {
LocaleChangeInterceptor localeChangeInterceptor =
new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("language");
return localeChangeInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry
registry) {
registry.addInterceptor(localeChangeInterceptor());
}
Messages Sources
Spring Boot application by default takes the message sources
from src/main/resources folder under the classpath. The default
locale message file name should be message.properties and
files for each locale should name as messages_XX.properties.
The “XX” represents the locale code.
HTML file
In the HTML file, use the syntax #{key} to display the messages
from the properties file.
Maven – pom.xml
<modelVersion>4.0.0</modelVersion>
<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 />
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
</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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Gradle – build.gradle
buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-
starter-web')
compile group: 'org.springframework.boot', name:
'spring-boot-starter-thymeleaf'
testCompile('org.springframework.boot:spring-boot-
starter-test')
}
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,
args);
}
}
package com.tutorialspoint.demo.controller;
import org.springframework.stereotype.Controller;
import
org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ViewController {
@RequestMapping("/locale")
public String locale() {
return "locale";
}
}
package com.tutorialspoint.demo;
import java.util.Locale;
import org.springframework.context.annotation.Bean;
import
org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import
org.springframework.web.servlet.config.annotation.Inter
ceptorRegistry;
import
org.springframework.web.servlet.config.annotation.WebMv
cConfigurerAdapter;
import
org.springframework.web.servlet.i18n.LocaleChangeInterc
eptor;
import
org.springframework.web.servlet.i18n.SessionLocaleResol
ver;
@Configuration
public class Internationalization extends
WebMvcConfigurerAdapter {
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver sessionLocaleResolver = new
SessionLocaleResolver();
sessionLocaleResolver.setDefaultLocale(Locale.US);
return sessionLocaleResolver;
}
@Bean
public LocaleChangeInterceptor
localeChangeInterceptor() {
LocaleChangeInterceptor localeChangeInterceptor =
new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("language");
return localeChangeInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry
registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset = "ISO-8859-1"/>
<title>Internationalization</title>
</head>
<body>
<h1 th:text = "#{welcome.text}"></h1>
</body>
</html>
You can create an executable JAR file, and run the Spring boot
application by using the following Maven or Gradle commands −
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
You will find that the application has started on the Tomcat port
8080.
Now hit the URL http://localhost:8080/locale in your web
browser and you can see the following output −
https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/
cron_expressions.htm
@SpringBootApplication
@EnableScheduling
package com.tutorialspoint.demo.scheduler;
import java.text.SimpleDateFormat;
import java.util.Date;
import
org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class Scheduler {
@Scheduled(cron = "0 * 9 * * ?")
public void cronJobSch() {
SimpleDateFormat sdf = new
SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date now = new Date();
String strDate = sdf.format(now);
System.out.println("Java cron job expression:: "
+ strDate);
}
}
The following screenshot shows how the application has started at
09:03:23 and for every one minute from that time the cron job
scheduler task has executed.
Fixed Rate
Fixed Rate scheduler is used to execute the tasks at the specific
time. It does not wait for the completion of previous task. The
values should be in milliseconds. The sample code is shown here
−
@Scheduled(fixedRate = 1000)
public void fixedRateSch() {
}
package com.tutorialspoint.demo.scheduler;
import java.text.SimpleDateFormat;
import java.util.Date;
import
org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class Scheduler {
@Scheduled(fixedRate = 1000)
public void fixedRateSch() {
SimpleDateFormat sdf = new
SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Fixed Delay
Fixed Delay scheduler is used to execute the tasks at a specific
time. It should wait for the previous task completion. The values
should be in milliseconds. A sample code is shown here −
Here, the initialDelay is the time after which the task will be
executed the first time after the initial delay value.
package com.tutorialspoint.demo.scheduler;
import java.text.SimpleDateFormat;
import java.util.Date;
import
org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class Scheduler {
@Scheduled(fixedDelay = 1000, initialDelay = 3000)
public void fixedDelaySch() {
SimpleDateFormat sdf = new
SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date now = new Date();
String strDate = sdf.format(now);
System.out.println("Fixed Delay scheduler:: " +
strDate);
}
}
You need to follow the steps given below to configure the HTTPS
and the port 443 in Spring Boot application −
Self-Signed Certificate
To create a self-signed certificate, Java Run Time environment
comes bundled with certificate management utility key tool. This
utility tool is used to create a Self-Signed certificate. It is shown in
the code given here −
Configure HTTPS
We need to provide the server port as 443, key-store file path,
key-store-password, key-store-type and key alias name into the
application.properties file. Observe the code given here −
server.port: 443
server.ssl.key-store: keystore.p12
server.ssl.key-store-password: springboot
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat
You can use the following code if you are using YAML properties
use below application.yml −
server:
port: 443
ssl:
key-store: keystore.p12
key-store-password: springboot
keyStoreType: PKCS12
keyAlias: tomcat
You can create an executable JAR file, and run the spring boot
application by using the following Maven or Gradle commands.
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
Now, the application has started on the Tomcat port 443 with
https as shown −
The code for main Spring Boot application class file is as shown
below −
package com.tutorialspoint.eurekaserver;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import
org.springframework.cloud.netflix.eureka.server.EnableE
urekaServer;
@SpringBootApplication
@EnableEurekaServer
public class EurekaserverApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaserverApplication.class,
args);
}
}
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifac
tId>
</dependency>
compile('org.springframework.cloud:spring-cloud-starter-eureka-server')
Maven pom.xml
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>eurekaserver</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>eurekaserver</name>
<description>Demo project for Spring
Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from
repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Edgware.RELEASE</spring-
cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-
server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Gradle – build.gradle
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
repositories {
mavenCentral()
}
ext {
springCloudVersion = 'Edgware.RELEASE'
}
dependencies {
compile('org.springframework.cloud:spring-cloud-
starter-eureka-server')
testCompile('org.springframework.boot:spring-boot-
starter-test')
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-
dependencies:${springCloudVersion}"
}
}
eureka.client.registerWithEureka = false
eureka.client.fetchRegistry = false
server.port = 8761
eureka:
client:
registerWithEureka: false
fetchRegistry: false
server:
port: 8761
Now, you can create an executable JAR file, and run the Spring
Boot application by using the Maven or Gradle commands shown
below −
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
You can find that the application has started on the Tomcat port
8761 as shown below −
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
compile('org.springframework.cloud:spring-cloud-starter-eureka')
package com.tutorialspoint.eurekaclient;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import
org.springframework.cloud.netflix.eureka.EnableEurekaCl
ient;
@SpringBootApplication
@EnableEurekaClient
public class EurekaclientApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaclientApplication.class,
args);
}
}
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka
instance:
preferIpAddress: true
spring:
application:
name: eurekaclient
eureka.client.serviceUrl.defaultZone =
http://localhost:8761/eureka
eureka.client.instance.preferIpAddress = true
spring.application.name = eurekaclient
Now, add the Rest Endpoint to return String in the main Spring
Boot application and the Spring Boot Starter web dependency in
build configuration file. Observe the code given below −
package com.tutorialspoint.eurekaclient;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import
org.springframework.cloud.netflix.eureka.EnableEurekaCl
ient;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableEurekaClient
@RestController
public class EurekaclientApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaclientApplication.class,
args);
}
@RequestMapping(value = "/")
public String home() {
return "Eureka Client application";
}
}
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>eurekaclient</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>eurekaclient</name>
<description>Demo project for Spring
Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from
repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Edgware.RELEASE</spring-
cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<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>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</projecta>
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
ext {
springCloudVersion = 'Edgware.RELEASE'
}
dependencies {
compile('org.springframework.cloud:spring-cloud-
starter-eureka')
testCompile('org.springframework.boot:spring-boot-
starter-test')
compile('org.springframework.boot:spring-boot-
starter-web')
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-
dependencies:${springCloudVersion}"
}
}
You can create an executable JAR file, and run the Spring Boot
application by using the following Maven or Gradle commands −
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
Now, the application has started on the Tomcat port 8080 and
Eureka Client application is registered with the Eureka Server as
shown below −
Hit the URL http://localhost:8761/ in your web browser and you
can see the Eureka Client application is registered with Eureka
Server.
package com.tutorialspoint.zuulserver;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import
org.springframework.cloud.netflix.zuul.EnableZuulProxy;
@SpringBootApplication
@EnableZuulProxy
public class ZuulserverApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulserverApplication.class,
args);
}
}
You will have to add the Spring Cloud Starter Zuul dependency in
our build configuration file.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
compile('org.springframework.cloud:spring-cloud-starter-zuul')
spring.application.name = zuulserver
zuul.routes.products.path = /api/demo/**
zuul.routes.products.url = http://localhost:8080/
server.port = 8111
yaml file users can use the application.yml file shown below −
server:
port: 8111
spring:
application:
name: zuulserver
zuul:
routes:
products:
path: /api/demo/**
url: http://localhost:8080/
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>zuulserver</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>zuulserver</name>
<description>Demo project for Spring
Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from
repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Edgware.RELEASE</spring-
cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
ext {
springCloudVersion = 'Edgware.RELEASE'
}
dependencies {
compile('org.springframework.cloud:spring-cloud-
starter-zuul')
testCompile('org.springframework.boot:spring-boot-
starter-test')
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-
dependencies:${springCloudVersion}"
}
}
You can create an executable JAR file, and run the Spring Boot
application by using the Maven or Gradle commands given below
−
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
Now, run the JAR file by using the command shown below −
You can find the application has started on the Tomcat port 8111
as shown here.
Maven users can add the below dependency into the pom.xml file.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
compile('org.springframework.cloud:spring-cloud-config-server')
package com.tutorialspoint.configserver;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import
org.springframework.cloud.config.server.EnableConfigSer
ver;
@SpringBootApplication
@EnableConfigServer
public class ConfigserverApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigserverApplication.class,
args);
}
}
server.port = 8888
spring.cloud.config.server.native.searchLocations=file:
///C:/configprop/
SPRING_PROFILES_ACTIVE=native
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>configserver</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>configserver</name>
<description>Demo project for Spring
Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from
repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Edgware.RELEASE</spring-
cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
<scope>import</scope>
</dependency>
</dependencies>
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
ext {
springCloudVersion = 'Edgware.RELEASE'
}
dependencies {
compile('org.springframework.cloud:spring-cloud-
config-server')
testCompile('org.springframework.boot:spring-boot-
starter-test')
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-
dependencies:${springCloudVersion}"
}
}
Now, create an executable JAR file, and run the Spring Boot
application by using the following Maven or Gradle commands −
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
For Gradle, use the command given below −
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
Maven users can add the following dependency into the pom.xml
file.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
compile('org.springframework.cloud:spring-cloud-starter-config')
package com.example.configclient;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import
org.springframework.cloud.context.config.annotation.Ref
reshScope;
@SpringBootApplication
@RefreshScope
public class ConfigclientApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigclientApplication.class,
args);
}
}
spring.application.name = config-client
spring.cloud.config.uri = http://localhost:8888
The code for writing a simple REST Endpoint to read the welcome
message from the configuration server is given below −
package com.example.configclient;
import
org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import
org.springframework.cloud.context.config.annotation.Ref
reshScope;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RefreshScope
@RestController
public class ConfigclientApplication {
@Value("${welcome.message}")
String welcomeText;
SpringApplication.run(ConfigclientApplication.class,
args);
}
@RequestMapping(value = "/")
public String welcomeText() {
return welcomeText;
}
}
You can create an executable JAR file, and run the Spring Boot
application by using the following Maven or Gradle commands −
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
Now, run the JAR file by using the command shown here:
Maven users can add the below dependency in your pom.xml file.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
management.security.enabled = false
management:
security:
enabled: false
If you want to use the separate port number for accessing the
Spring boot actutator endpoints add the management port
number in application.properties file.
management.port = 9000
management:
port: 9000
Now, you can create an executable JAR file, and run the Spring
Boot application by using the following Maven or Gradle
commands.
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
Now, you can run the JAR file by using the following command −
Now, the application has started on the Tomcat port 8080. Note
that if you specified the management port number, then same
application is running on two different port numbers.
ENDPOIN
USAGE
TS
To view the application metrics such as memory used, memory free, threads,
/metrics
classes, system uptime etc.
/beans To view the Spring beans and its types, scopes and dependency.
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server</artifactId>
<version>1.5.5</version>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server-ui</artifactId>
<version>1.5.5</version>
</dependency>
package com.tutorialspoint.adminserver;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import
de.codecentric.boot.admin.config.EnableAdminServer;
@SpringBootApplication
@EnableAdminServer
public class AdminserverApplication {
public static void main(String[] args) {
SpringApplication.run(AdminserverApplication.class,
args);
}
}
server.port = 9090
spring.application.name = adminserver
For YAML users, use the following properties to define the port
number and application name in application.yml file.
server:
port: 9090
spring:
application:
name: adminserver
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>adminserver</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>adminserver</name>
<description>Demo project for Spring
Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath /> <!-- lookup parent from
repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server</artifactId>
<version>1.5.5</version>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server-ui</artifactId>
<version>1.5.5</version>
</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>
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-
starter')
compile group: 'de.codecentric', name: 'spring-boot-
admin-server', version: '1.5.5'
compile group: 'de.codecentric', name: 'spring-boot-
admin-server-ui', version: '1.5.5'
testCompile('org.springframework.boot:spring-boot-
starter-test')
}
You can create an executable JAR file, and run the Spring Boot
application by using the following Maven or Gradle commands −
After “BUILD SUCCESS”, you can find the JAR file under target
directory.
After “BUILD SUCCESSFUL”, you can find the JAR file under
build/libs directory.
Now, run the JAR file by using the command given below −
Now hit the below URL from your web browser and see the Admin
Server UI.
http://localhost:9090/
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>1.5.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Gradle users can add the following dependencies in your
build.gradle file.
Now, add the Spring Boot Admin Server URL into your application
properties file.
spring.boot.admin.url = http://localhost:9090/
spring:
boot:
admin:
url: http://localhost:9000/
Now, create an executable JAR file, and run the Spring Boot
application by using the following Maven or Gradle commands.
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
Now hit the following URL from your web browser and see your
spring Boot application is registered with Spring Boot Admin
Server.
http://localhost:9090/
Now, click the Details button and the see the actuator endpoints
in Admin Server UI.
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
package com.tutorialspoint.swaggerdemo;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import
springfox.documentation.swagger2.annotations.EnableSwag
ger2;
@SpringBootApplication
@EnableSwagger2
public class SwaggerDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SwaggerDemoApplication.class,
args);
}
}
@Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com.tutorialspoint.swagg
erdemo")).build();
}
Now, add this bean in main Spring Boot application class file itself
and your main Spring Boot application class will look as shown
below −
package com.tutorialspoint.swaggerdemo;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import org.springframework.context.annotation.Bean;
import
springfox.documentation.builders.RequestHandlerSelector
s;
import springfox.documentation.spi.DocumentationType;
import
springfox.documentation.spring.web.plugins.Docket;
import
springfox.documentation.swagger2.annotations.EnableSwag
ger2;
@SpringBootApplication
@EnableSwagger2
public class SwaggerDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SwaggerDemoApplication.class,
args);
}
@Bean
public Docket productApi() {
return new
Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com
.tutorialspoint.swaggerdemo")).build();
}
}
Now, add the below Spring Boot Starter Web dependency in your
build configuration file to write a REST Endpoints as shown below
−
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
compile('org.springframework.boot:spring-boot-starter-web')
Now, the code to build two simple RESTful web services GET and
POST in Rest Controller file is shown here −
package com.tutorialspoint.swaggerdemo;
import java.util.ArrayList;
import java.util.List;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RequestMethod;
import
org.springframework.web.bind.annotation.RestController;
@RestController
public class SwaggerAPIController {
@RequestMapping(value = "/products", method =
RequestMethod.GET)
public List<String> getProducts() {
List<String> productsList = new ArrayList<>();
productsList.add("Honey");
productsList.add("Almond");
return productsList;
}
@RequestMapping(value = "/products", method =
RequestMethod.POST)
public String createProduct() {
return "Product is saved successfully";
}
}
Maven – pom.xml
<groupId>com.tutorialspoint</groupId>
<artifactId>swagger-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>swagger-demo</name>
<description>Demo project for Spring
Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath /> <!-- lookup parent from
repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
</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>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Gradle – build.gradle
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.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')
compile group: 'io.springfox', name: 'springfox-
swagger2', version: '2.7.0'
compile group: 'io.springfox', name: 'springfox-
swagger-ui', version: '2.7.0'
}
You can create an executable JAR file, and run the Spring Boot
application by using the following Maven or Gradle commands.
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
Now, run the JAR file by using the command shown here −
Now, the application will start on the Tomcat port 8080 as shown
−
Now, hit the URL in your web browser and see the Swagger API
functionalities.
http://localhost:8080/swagger-ui.html
Spring Boot - Creating Docker
Image
Docker is a container management service that eases building
and deployment. If you are a beginner to Docker, you can learn
about is in detail at this link
− https://www.tutorialspoint.com/docker/index.htm
Create Dockerfile
First, create a file with the name Dockerfile under the
directories src/main/docker with the contents shown below.
Note that this file is important to create a Docker image.
FROM java:8
VOLUME /tmp
ADD dockerapp-0.0.1-SNAPSHOT.jar app.jar
RUN bash -c 'touch /app.jar'
ENTRYPOINT
["java","-Djava.security.egd=file:/dev/./urandom","-
jar","/app.jar"]
Maven
For Maven, add the Docker Maven plugin into your build
configuration file pom.xml
<properties>
<docker.image.prefix>spring-boot-tutorialspoint</docker
.image.prefix>
</properties>
<build>
<plugins>
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>1.0.0</version>
<configuration>
<imageName>${docker.image.prefix}/$
{project.artifactId}</imageName>
<dockerDirectory>src/main/docker</dockerDirectory>
<resources>
<resource>
<directory>$
{project.build.directory}</directory>
<include>$
{project.build.finalName}.jar</include>
</resource>
</resources>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>dockerapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>dockerapp</name>
<description>Demo project for Spring
Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath /> <!-- lookup parent from
repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
<docker.image.prefix>spring-boot-
tutorialspoint</docker.image.prefix>
</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>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>1.0.0</version>
<configuration>
<imageName>${docker.image.prefix}/$
{project.artifactId}</imageName>
<dockerDirectory>src/main/docker</dockerDirectory>
<resources>
<resource>
<directory>$
{project.build.directory}</directory>
<include>$
{project.build.finalName}.jar</include>
</resource>
</resources>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
After build success, you can see the output on the console as
shown below −
Gradle
To build a Docker image by using Gradle build configuration, we
need to add the docker plugin and need to write a
task buildDocker to create a Docker image.
The code for Gradle Docker configuration is given below.
buildscript {
.....
dependencies {
.....
classpath('se.transmode.gradle:gradle-
docker:1.2')
}
}
group = 'spring-boot-tutorialspoint'
.....
apply plugin: 'docker'
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
classpath('se.transmode.gradle:gradle-
docker:1.2')
}
}
group = 'spring-boot-tutorialspoint'
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')
}
task buildDocker(type: Docker, dependsOn: build) {
applicationName = jar.baseName
dockerfile = file('src/main/docker/Dockerfile')
doFirst {
copy {
from jar
into stageDir
}
}
}
[application-name,traceid,spanid,zipkin-export]
Where,
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
compile('org.springframework.cloud:spring-cloud-starter-sleuth')
Now, add the Logs into your Spring Boot application Rest
Controller class file as shown here −
package com.tutorialspoint.sleuthapp;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class SleuthappApplication {
private static final Logger LOG =
Logger.getLogger(SleuthappApplication.class.getName());
public static void main(String[] args) {
SpringApplication.run(SleuthappApplication.class,
args);
}
@RequestMapping("/")
public String index() {
LOG.log(Level.INFO, "Index API is calling");
return "Welcome Sleuth!";
}
}
spring.application.name = tracinglogs
Maven – pom.xml
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>sleuthapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>sleuthapp</name>
<description>Demo project for Spring
Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from
repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Edgware.RELEASE</spring-
cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<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>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Gradle – build.gradle
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
ext {
springCloudVersion = 'Edgware.RELEASE'
}
dependencies {
compile('org.springframework.cloud:spring-cloud-
starter-sleuth')
compile('org.springframework.boot:spring-boot-
starter-web')
testCompile('org.springframework.boot:spring-boot-
starter-test')
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-
dependencies:${springCloudVersion}"
}
}
You can create an executable JAR file, and run the Spring Boot
application by using the following Maven or Gradle commands.
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
Now, run the JAR file by using the command shown here −
Now, hit the URL in your web browser and see the output in
console log.
http://localhost:8080/
You can see the following logs in the console window. Observe
that log is printed in the following format [application-name,
traceid, spanid, zipkin-export]
Zipkin Server
Zipkin is an application that monitors and manages the Spring
Cloud Sleuth logs of your Spring Boot application. To build a
Zipkin server, we need to add the Zipkin UI and Zipkin Server
dependencies in our build configuration file.
<dependency>
<groupId>io.zipkin.java</groupId>
<artifactId>zipkin-server</artifactId>
</dependency>
<dependency>
<groupId>io.zipkin.java</groupId>
<artifactId>zipkin-autoconfigure-ui</artifactId>
</dependency>
Gradle users can add the below dependency in your build.gradle
file −
compile('io.zipkin.java:zipkin-autoconfigure-ui')
compile('io.zipkin.java:zipkin-server')
server.port = 9411
server:
port: 9411
package com.tutorialspoint.zipkinapp;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import zipkin.server.EnableZipkinServer;
@SpringBootApplication
@EnableZipkinServer
public class ZipkinappApplication {
public static void main(String[] args) {
SpringApplication.run(ZipkinappApplication.class,
args);
}
}
Maven – pom.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-
instance"
xsi:schemaLocation =
"http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>zipkinapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>zipkinapp</name>
<description>Demo project for Spring
Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath /> <!-- lookup parent from
repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Edgware.RELEASE</spring-
cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>io.zipkin.java</groupId>
<artifactId>zipkin-server</artifactId>
</dependency>
<dependency>
<groupId>io.zipkin.java</groupId>
<artifactId>zipkin-autoconfigure-ui</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Gradle – build.gradle
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
ext {
springCloudVersion = 'Edgware.RELEASE'
}
dependencies {
compile('io.zipkin.java:zipkin-autoconfigure-ui')
compile('io.zipkin.java:zipkin-server')
testCompile('org.springframework.boot:spring-boot-
starter-test')
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-
dependencies:${springCloudVersion}"
}
}
You can create an executable JAR file, and run the Spring Boot
application by using the below Maven or Gradle commands −
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
Now, hit the below URL and see the Zipkin server UI.
http://localhost:9411/zipkin/
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-sleuth-zipkin</artifactId>
</dependency>
compile('org.springframework.cloud:spring-cloud-sleuth-zipkin')
@Bean
public AlwaysSampler defaultSampler() {
return new AlwaysSampler();
}
spring.zipkin.baseUrl = http://localhost:9411/zipkin/
Then, provide the trace id and find the traces in Zipkin UI.
http://localhost:9411/zipkin/traces/{traceid}/
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
compile('org.flywaydb:flyway-core')
compile('org.springframework.boot:spring-boot-starter-
jdbc')
compile('org.springframework.boot:spring-boot-starter-
web')
compile('mysql:mysql-connector-java')
spring.application.name = flywayapp
spring.datasource.driverClassName =
com.mysql.jdbc.Driver
spring.datasource.url =
jdbc:mysql://localhost:3306/USERSERVICE?
autoreconnect=true
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.testOnBorrow = true
spring.datasource.testWhileIdle = true
spring.datasource.timeBetweenEvictionRunsMillis = 60000
spring.datasource.minEvictableIdleTimeMillis = 30000
spring.datasource.validationQuery = SELECT 1
spring.datasource.max-active = 15
spring.datasource.max-idle = 10
spring.datasource.max-wait = 8000
flyway.url = jdbc:mysql://localhost:3306/mysql
flyway.schemas = USERSERVICE
flyway.user = root
flyway.password = root
spring:
application:
name: flywayapp
datasource:
driverClassName: com.mysql.jdbc.Driver
url: "jdbc:mysql://localhost:3306/USERSERVICE?
autoreconnect=true"
password: "root"
username: "root"
testOnBorrow: true
testWhileIdle: true
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 30000
validationQuery: SELECT 1
max-active: 15
max-idle: 10
max-wait: 8000
flyway:
url: jdbc:mysql://localhost:3306/mysql
schemas: USERSERVICE
user: "root"
password: "root"
The main Spring Boot application class file code is given below −
package com.tutorialspoint.flywayapp;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
@SpringBootApplication
public class FlywayappApplication {
public static void main(String[] args) {
SpringApplication.run(FlywayappApplication.class,
args);
}
}
Maven – pom.xml
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>flywayapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>flywayapp</name>
<description>Demo project for Spring
Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from
repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Gradle – build.gradle
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.flywaydb:flyway-core')
compile('org.springframework.boot:spring-boot-
starter-jdbc')
compile('org.springframework.boot:spring-boot-
starter-web')
compile('mysql:mysql-connector-java')
testCompile('org.springframework.boot:spring-boot-
starter-test')
}
You can create an executable JAR file, and run the Spring Boot
application by using the Maven or Gradle commands given below
−
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
For Gradle, you can use the command shown here −
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
Now, Tomcat started on the port 8080 and in the console window
you can see the flyway database logs as shown here.
Maven users can add the following dependency into the pom.xml
file.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
compile('org.springframework.boot:spring-boot-starter-mail')
The code of main Spring Boot application class file is given below
−
package com.tutorialspoint.emailapp;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
@SpringBootApplication
public class EmailappApplication {
public static void main(String[] args) {
SpringApplication.run(EmailappApplication.class,
args);
}
}
You can write a simple Rest API to send to email in Rest Controller
class file as shown.
package com.tutorialspoint.emailapp;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RestController;
@RestController
public class EmailController {
@RequestMapping(value = "/sendemail")
public String sendEmail() {
return "Email sent successfully";
}
}
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[email protected]"));
msg.setSubject("Tutorials point email");
msg.setContent("Tutorials point email",
"text/html");
msg.setSentDate(new Date());
attachPart.attachFile("/var/tmp/image19.png");
multipart.addBodyPart(attachPart);
msg.setContent(multipart);
Transport.send(msg);
}
Now, call the above sendmail() method from the Rest API as
shown −
@RequestMapping(value = "/sendemail")
public String sendEmail() throws AddressException,
MessagingException, IOException {
sendmail();
return "Email sent successfully";
}
Maven – pom.xml
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>emailapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>emailapp</name>
<description>Demo project for Spring
Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from
repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
</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-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</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>
Gradle – build.gradle
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-
starter-web')
compile('org.springframework.boot:spring-boot-
starter-mail')
testCompile('org.springframework.boot:spring-boot-
starter-test')
}
Now, you can create an executable JAR file, and run the Spring
Boot application by using the Maven or Gradle commands shown
below −
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
Now, run the JAR file by using the command given below −
You can see that the application has started on the Tomcat port
8080.
Now hit the following URL from your web browser and you will
receive an email.
http://localhost:8080/sendemail
Spring Boot - Hystrix
Hystrix is a library from Netflix. Hystrix isolates the points of
access between the services, stops cascading failures across
them and provides the fallback options.
For example, when you are calling a 3rd party application, it takes
more time to send the response. So at that time, the control goes
to the fallback method and returns the custom response to your
application.
In this chapter you are going to see How to implement the Hystrix
in a Spring Boot application.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
compile('org.springframework.cloud:spring-cloud-starter-hystrix')
The main Spring Boot application class file code is given below −
package com.tutorialspoint.hystrixapp;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import
org.springframework.cloud.netflix.hystrix.EnableHystrix
;
@SpringBootApplication
@EnableHystrix
public class HystrixappApplication {
public static void main(String[] args) {
SpringApplication.run(HystrixappApplication.class,
args);
}
}
Now write a simple Rest Controller such that it returns the String
after 3 seconds from the requested time.
@RequestMapping(value = "/")
public String hello() throws InterruptedException {
Thread.sleep(3000);
return "Welcome Hystrix";
}
@HystrixCommand(fallbackMethod = "fallback_hello",
commandProperties = {
@HystrixProperty(name =
"execution.isolation.thread.timeoutInMilliseconds",
value = "1000")
})
The complete Rest Controller class file that contains REST API and
Hystrix properties is shown here −
@RequestMapping(value = "/")
@HystrixCommand(fallbackMethod = "fallback_hello",
commandProperties = {
@HystrixProperty(name =
"execution.isolation.thread.timeoutInMilliseconds",
value = "1000")
})
public String hello() throws InterruptedException {
Thread.sleep(3000);
return "Welcome Hystrix";
}
private String fallback_hello() {
return "Request fails. It takes long time to
response";
}
package com.tutorialspoint.hystrixapp;
import org.springframework.boot.SpringApplication;
import
com.netflix.hystrix.contrib.javanica.annotation.Hystrix
Property;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import
org.springframework.cloud.netflix.hystrix.EnableHystrix
;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RestController;
import
com.netflix.hystrix.contrib.javanica.annotation.Hystrix
Command;
@SpringBootApplication
@EnableHystrix
@RestController
public class HystrixappApplication {
public static void main(String[] args) {
SpringApplication.run(HystrixappApplication.class,
args);
}
@RequestMapping(value = "/")
@HystrixCommand(fallbackMethod = "fallback_hello",
commandProperties = {
@HystrixProperty(name =
"execution.isolation.thread.timeoutInMilliseconds",
value = "1000")
})
public String hello() throws InterruptedException {
Thread.sleep(3000);
return "Welcome Hystrix";
}
private String fallback_hello() {
return "Request fails. It takes long time to
response";
}
}
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>hystrixapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>hystrixapp</name>
<description>Demo project for Spring
Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from
repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Edgware.RELEASE</spring-
cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
<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>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Gradle – build.gradle
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
ext {
springCloudVersion = 'Edgware.RELEASE'
}
dependencies {
compile('org.springframework.cloud:spring-cloud-
starter-hystrix')
compile('org.springframework.boot:spring-boot-
starter-web')
testCompile('org.springframework.boot:spring-boot-
starter-test')
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-
dependencies:${springCloudVersion}"
}
}
You can create an executable JAR file, and run the Spring Boot
application by using the following Maven or Gradle commands −
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
Now, run the JAR file by using the command given below −
This will start the application on the Tomcat port 8080 as shown
below −
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>sockjs-client</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>stomp-websocket</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7</version> </dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.1.0</version>
</dependency>
compile("org.springframework.boot:spring-boot-starter-
websocket")
compile("org.webjars:webjars-locator")
compile("org.webjars:sockjs-client:1.0.2")
compile("org.webjars:stomp-websocket:2.3.3")
compile("org.webjars:bootstrap:3.3.7")
compile("org.webjars:jquery:3.1.0")
package com.tutorialspoint.websocketapp;
import
org.springframework.messaging.handler.annotation.Messag
eMapping;
import
org.springframework.messaging.handler.annotation.SendTo
;
import org.springframework.stereotype.Controller;
@Controller
public class GreetingController {
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message)
throws Exception {
Thread.sleep(1000); // simulated delay
return new Greeting("Hello, " + message.getName()
+ "!");
}
}
Now, configure Spring for STOMP messaging. Write a
WebSocketConfig class file that extends the
AbstractWebSocketMessageBrokerConfigurer class as shown
below.
package com.tutorialspoint.websocketapp;
import
org.springframework.context.annotation.Configuration;
import
org.springframework.messaging.simp.config.MessageBroker
Registry;
import
org.springframework.web.socket.config.annotation.Abstra
ctWebSocketMessageBrokerConfigurer;
import
org.springframework.web.socket.config.annotation.Enable
WebSocketMessageBroker;
import
org.springframework.web.socket.config.annotation.StompE
ndpointRegistry;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends
AbstractWebSocketMessageBrokerConfigurer {
@Override
public void
configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void
registerStompEndpoints(StompEndpointRegistry registry)
{
registry.addEndpoint("/tutorialspoint-
websocket").withSockJS();
}
}
<!DOCTYPE html>
<html>
<head>
<title>Hello WebSocket</title>
<link href =
"/webjars/bootstrap/css/bootstrap.min.css" rel =
"stylesheet">
<link href = "/main.css" rel = "stylesheet">
<script src =
"/webjars/jquery/jquery.min.js"></script>
<script src =
"/webjars/sockjs-client/sockjs.min.js"></script>
<script src =
"/webjars/stomp-websocket/stomp.min.js"></script>
<script src = "/app.js"></script>
</head>
<body>
<noscript>
<h2 style = "color: #ff0000">
Seems your browser doesn't support
Javascript! Websocket relies on Javascript being
enabled. Please enable Javascript and
reload this page!
</h2>
</noscript>
<div id = "main-content" class = "container">
<div class = "row">
<div class = "col-md-6">
<form class = "form-inline">
<div class = "form-group">
<label for = "connect">WebSocket
connection:</label>
<button id = "connect" class =
"btn btn-default" type = "submit">Connect</button>
<button id = "disconnect" class =
"btn btn-default" type = "submit" disabled =
"disabled">Disconnect
</button>
</div>
</form>
</div>
function setConnected(connected) {
$("#connect").prop("disabled", connected);
$("#disconnect").prop("disabled", !connected);
if (connected) {
$("#conversation").show();
} else {
$("#conversation").hide();
}
$("#greetings").html("");
}
function connect() {
var socket = new SockJS('/tutorialspoint-
websocket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/greetings',
function (greeting) {
showGreeting(JSON.parse(greeting.body).content);
});
});
}
function disconnect() {
if (stompClient !== null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function sendName() {
stompClient.send("/app/hello", {},
JSON.stringify({'name': $("#name").val()}));
}
function showGreeting(message) {
$("#greetings").append("<tr><td>" + message +
"</td></tr>");
}
$(function () {
$( "form" ).on('submit', function (e)
{e.preventDefault();});
$( "#connect" ).click(function() { connect(); });
$( "#disconnect" ).click(function()
{ disconnect(); });
$( "#send" ).click(function() { sendName(); });
});
package com.tutorialspoint.websocketapp;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
@SpringBootApplication
public class WebsocketappApplication {
public static void main(String[] args) {
SpringApplication.run(WebsocketappApplication.class,
args);
}
}
Maven – pom.xml
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>websocketapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>websocketapp</name>
<description>Demo project for Spring
Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>sockjs-client</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>stomp-websocket</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Gradle – build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:1.5.9.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
jar {
baseName = 'websocketapp'
version = '0.1.0'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile("org.springframework.boot:spring-boot-
starter-websocket")
compile("org.webjars:webjars-locator")
compile("org.webjars:sockjs-client:1.0.2")
compile("org.webjars:stomp-websocket:2.3.3")
compile("org.webjars:bootstrap:3.3.7")
compile("org.webjars:jquery:3.1.0")
testCompile("org.springframework.boot:spring-boot-
starter-test")
}
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
</dependency>
Now, add the simple CSV data file under classpath resources –
src/main/resources and name the file as file.csv as shown −
William,John
Mike, Sebastian
Lawarance, Lime
package com.tutorialspoint.batchservicedemo;
public class User {
private String lastName;
private String firstName;
public User() {
}
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return "firstName: " + firstName + ", lastName: " + lastName;
}
}
package com.tutorialspoint.batchservicedemo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
@Override
public User process(final User user) throws
Exception {
final String firstName =
user.getFirstName().toUpperCase();
final String lastName =
user.getLastName().toUpperCase();
final User transformedPerson = new
User(firstName, lastName);
package com.tutorialspoint.batchservicedemo;
import javax.sql.DataSource;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import
org.springframework.batch.core.configuration.annotation
.EnableBatchProcessing;
import
org.springframework.batch.core.configuration.annotation
.JobBuilderFactory;
import
org.springframework.batch.core.configuration.annotation
.StepBuilderFactory;
import
org.springframework.batch.core.launch.support.RunIdIncr
ementer;
import
org.springframework.batch.item.database.BeanPropertyIte
mSqlParameterSourceProvider;
import
org.springframework.batch.item.database.JdbcBatchItemWr
iter;
import
org.springframework.batch.item.file.FlatFileItemReader;
import
org.springframework.batch.item.file.mapping.BeanWrapper
FieldSetMapper;
import
org.springframework.batch.item.file.mapping.DefaultLine
Mapper;
import
org.springframework.batch.item.file.transform.Delimited
LineTokenizer;
import
org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import
org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
@Configuration
@EnableBatchProcessing
public class BatchConfiguration {
@Autowired
public JobBuilderFactory jobBuilderFactory;
@Autowired
public StepBuilderFactory stepBuilderFactory;
@Autowired
public DataSource dataSource;
@Bean
public FlatFileItemReader<User> reader() {
FlatFileItemReader<User> reader = new
FlatFileItemReader<User>();
reader.setResource(new
ClassPathResource("file.csv"));
reader.setLineMapper(new
DefaultLineMapper<User>() {
{
setLineTokenizer(new
DelimitedLineTokenizer() {
{
setNames(new String[] { "firstName",
"lastName" });
}
});
setFieldSetMapper(new
BeanWrapperFieldSetMapper<User>() {
{
setTargetType(User.class);
}
});
}
});
return reader;
}
@Bean
public UserItemProcessor processor() {
return new UserItemProcessor();
}
@Bean
public JdbcBatchItemWriter<User> writer() {
JdbcBatchItemWriter<User> writer = new
JdbcBatchItemWriter<User>();
writer.setItemSqlParameterSourceProvider(new
BeanPropertyItemSqlParameterSourceProvider<User>());
writer.setSql("INSERT INTO USERS (first_name,
last_name) VALUES (:firstName, :lastName)");
writer.setDataSource(dataSource);
return writer;
}
@Bean
public Job
importUserJob(JobCompletionNotificationListener
listener) {
return
jobBuilderFactory.get("importUserJob").incrementer(
new
RunIdIncrementer()).listener(listener).flow(step1()).en
d().build();
}
@Bean
public Step step1() {
return stepBuilderFactory.get("step1").<User,
User>chunk(10).reader(reader()).processor(processor()).
writer(writer()).build();
}
}
The reader() method is used to read the data from the CSV file
and writer() method is used to write a data into the SQL.
package com.tutorialspoint.batchservicedemo;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import
org.springframework.batch.core.listener.JobExecutionLis
tenerSupport;
import
org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
@Component
public class JobCompletionNotificationListener extends
JobExecutionListenerSupport {
private static final Logger log =
LoggerFactory.getLogger(JobCompletionNotificationListen
er.class);
private final JdbcTemplate jdbcTemplate;
@Autowired
public
JobCompletionNotificationListener(JdbcTemplate
jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public void afterJob(JobExecution jobExecution) {
if (jobExecution.getStatus() ==
BatchStatus.COMPLETED) {
log.info("!!! JOB FINISHED !! It's time to
verify the results!!");
@Override
public User mapRow(ResultSet rs, int row)
throws SQLException {
return new User(rs.getString(1),
rs.getString(2));
}
});
Now, create an executable JAR file, and run the Spring Boot
application by using the following Maven or Gradle commands.
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
Producing Messages
To produce messages into Apache Kafka, we need to define the
Configuration class for Producer configuration as shown −
package com.tutorialspoint.kafkademo;
import java.util.HashMap;
import java.util.Map;
import
org.apache.kafka.clients.producer.ProducerConfig;
import
org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.context.annotation.Bean;
import
org.springframework.context.annotation.Configuration;
import
org.springframework.kafka.core.DefaultKafkaProducerFact
ory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;
@Configuration
public class KafkaProducerConfig {
@Bean
public ProducerFactory<String, String>
producerFactory() {
Map<String, Object> configProps = new
HashMap<>();
configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG
, "localhost:9092");
configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CON
FIG, StringSerializer.class);
configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_C
ONFIG, StringSerializer.class);
return new
DefaultKafkaProducerFactory<>(configProps);
}
@Bean
public KafkaTemplate<String, String> kafkaTemplate()
{
return new KafkaTemplate<>(producerFactory());
}
}
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
package com.tutorialspoint.kafkademo;
import java.util.HashMap;
import java.util.Map;
import
org.apache.kafka.clients.consumer.ConsumerConfig;
import
org.apache.kafka.common.serialization.StringDeserialize
r;
import org.springframework.context.annotation.Bean;
import
org.springframework.context.annotation.Configuration;
import
org.springframework.kafka.annotation.EnableKafka;
import
org.springframework.kafka.config.ConcurrentKafkaListene
rContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import
org.springframework.kafka.core.DefaultKafkaConsumerFact
ory;
@EnableKafka
@Configuration
public class KafkaConsumerConfig {
@Bean
public ConsumerFactory<String, String>
consumerFactory() {
Map<String, Object> props = new HashMap<>();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
"localhost:2181");
props.put(ConsumerConfig.GROUP_ID_CONFIG, "group-
id");
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
StringDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFI
G, StringDeserializer.class);
return new DefaultKafkaConsumerFactory<>(props);
}
@Bean
public
ConcurrentKafkaListenerContainerFactory<String, String>
kafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String,
String>
factory = new
ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory());
return factory;
}
}
Your main Spring Boot application class file code is given below −
package com.tutorialspoint.kafkademo;
import
org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import
org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
@SpringBootApplication
public class KafkaDemoApplication implements
ApplicationRunner {
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
Maven – pom.xml
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>kafka-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>kafka-demo</name>
<description>Demo project for Spring
Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath /> <!-- lookup parent from
repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>2.1.0.RELEASE</version>
</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 – build.gradle
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-
starter')
compile group: 'org.springframework.kafka', name:
'spring-kafka', version: '2.1.0.RELEASE'
testCompile('org.springframework.boot:spring-boot-
starter-test')
}
Now, create an executable JAR file, and run the Spring Boot
application by using the below Maven or Gradle commands as
shown −
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
In this chapter, you are going to learn how to implement the SMS
sending and making voice calls by using Spring Boot with Twilio.
Note − We used the Trail account in Twilio to send the SMS and
making voice calls. You can learn more about Twilio
at www.twilio.com.
<dependency>
<groupId>com.twilio.sdk</groupId>
<artifactId>twilio</artifactId>
<version>7.16.1</version>
</dependency>
static {
Twilio.init(ACCOUNT_SID, AUTH_ID);
}
Sending SMS
To send the SMS, we need to provide a from-number and to-
number to the Message.create() method. Message body content
also we need to provide for the method Message.creator()as
shown −
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Message;
import com.twilio.type.PhoneNumber;
@SpringBootApplication
public class SmsdemoApplication implements
ApplicationRunner {
private final static String ACCOUNT_SID = "<your-
account-sid>";
private final static String AUTH_ID = "<your-auth-
id>";
static {
Twilio.init(ACCOUNT_SID, AUTH_ID);
}
public static void main(String[] args) {
SpringApplication.run(SmsdemoApplication.class,
args);
}
@Override
public void run(ApplicationArguments arg0) throws
Exception {
Message.creator(new PhoneNumber("to-number"), new
PhoneNumber("from-number"),
"Message from Spring Boot
Application").create();
}
}
Maven – pom.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-
instance"
xsi:schemaLocation =
"http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>smsdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>smsdemo</name>
<description>Demo project for Spring
Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath /> <!-- lookup parent from
repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.twilio.sdk</groupId>
<artifactId>twilio</artifactId>
<version>7.16.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Gradle – build.gradle
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-
starter')
testCompile('org.springframework.boot:spring-boot-
starter-test')
compile group: "com.twilio.sdk", name:"twilio",
version: "7.11.+"
}
You can create an executable JAR file, and run the spring boot
application by using the following Maven or Gradle commands −
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
Voice Calls
To make voice calls by using Twilio, we need to call the
Call.creator() method. For this method, we need to provide a to-
number, from-number, and voice-note as shown here.
The code for main Spring Boot application class file is given
below.
package com.tutorialspoint.smsdemo;
import java.net.URI;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Call;
import com.twilio.type.PhoneNumber;
@SpringBootApplication
public class SmsdemoApplication implements
ApplicationRunner {
private final static String ACCOUNT_SID = "<ACCOUNT-
SID>";
private final static String AUTH_ID = "AUTH-ID";
static {
Twilio.init(ACCOUNT_SID, AUTH_ID);
}
public static void main(String[] args) {
SpringApplication.run(SmsdemoApplication.class,
args);
}
@Override
public void run(ApplicationArguments arg0) throws
Exception {
Call.creator(new PhoneNumber("<to-number>"), new
PhoneNumber("<from-number>"),
new
URI("http://demo.twilio.com/docs/voice.xml")).create();
}
}
Maven – pom.xml
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>smsdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>smsdemo</name>
<description>Demo project for Spring
Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath /> <!-- lookup parent from
repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.twilio.sdk</groupId>
<artifactId>twilio</artifactId>
<version>7.16.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Gradle – build.gradle
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-
starter')
testCompile('org.springframework.boot:spring-boot-
starter-test')
compile group: "com.twilio.sdk", name:"twilio",
version: "7.11.+"
}
You can create an executable JAR file, and run the Spring Boot
application by using the following Maven or Gradle commands.
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
Now, run the JAR file by using the command given here −
Press any key after attending the call, you will hear the voice note
from https://demo.twilio.com/docs/voice.xml
Note − In this example, we used the Trail account. So, you should
verify the numbers before making calls.
In this tutorial, we are going to see how to write a unit test case
by using Mockito and Web Controller.
Mockito
For injecting Mockito Mocks into Spring Beans, we need to add the
Mockito-core dependency in our build configuration file.
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.13.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
package com.tutorialspoint.mockitodemo;
import org.springframework.stereotype.Service;
@Service
public class ProductService {
public String getProductName() {
return "Honey";
}
}
Now, inject the ProductService class into another Service class file
as shown.
package com.tutorialspoint.mockitodemo;
import
org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class OrderService {
@Autowired
ProductService productService;
package com.tutorialspoint.mockitodemo;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
@SpringBootApplication
public class MockitoDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MockitoDemoApplication.class,
args);
}
}
package com.tutorialspoint.mockitodemo;
import org.mockito.Mockito;
import org.springframework.context.annotation.Bean;
import
org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
@Profile("test")
@Configuration
public class ProductServiceTestConfiguration {
@Bean
@Primary
public ProductService productService() {
return Mockito.mock(ProductService.class);
}
}
Now, you can write a Unit Test case for Order Service under
the src/test/resources package.
package com.tutorialspoint.mockitodemo;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import
org.springframework.test.context.junit4.SpringJUnit4Cla
ssRunner;
@SpringBootTest
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
public class MockitoDemoApplicationTests {
@Autowired
private OrderService orderService;
@Autowired
private ProductService productService;
@Test
public void
whenUserIdIsProvided_thenRetrievedNameIsCorrect() {
Mockito.when(productService.getProductName()).thenRetur
n("Mock Product Name");
String testName = orderService.getProductName();
Assert.assertEquals("Mock Product Name",
testName);
}
}
Maven – pom.xml
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>mockito-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>mockito-demo</name>
<description>Demo project for Spring
Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath /> <!-- lookup parent from
repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.13.0</version>
</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 – build.gradle
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-
starter')
compile group: 'org.mockito', name: 'mockito-core',
version: '2.13.0'
testCompile('org.springframework.boot:spring-boot-
starter-test')
}
You can create an executable JAR file, and run the Spring Boot
application by using the following Maven or Gradle1 commands.
For Writing a Unit Test, we need to add the Spring Boot Starter
Test dependency in your build configuration file as shown below.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
testCompile('org.springframework.boot:spring-boot-starter-test')
package com.tutorialspoint.demo;
import java.io.IOException;
import org.junit.runner.RunWith;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.boot.test.context.SpringBootTest;
import
org.springframework.test.context.junit4.SpringJUnit4Cla
ssRunner;
import
org.springframework.test.context.web.WebAppConfiguratio
n;
import org.springframework.test.web.servlet.MockMvc;
import
org.springframework.test.web.servlet.setup.MockMvcBuild
ers;
import
org.springframework.web.context.WebApplicationContext;
import com.fasterxml.jackson.core.JsonParseException;
import
com.fasterxml.jackson.core.JsonProcessingException;
import
com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DemoApplication.class)
@WebAppConfiguration
public abstract class AbstractTest {
protected MockMvc mvc;
@Autowired
WebApplicationContext webApplicationContext;
protected void setUp() {
mvc =
MockMvcBuilders.webAppContextSetup(webApplicationContex
t).build();
}
protected String mapToJson(Object obj) throws
JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(obj);
}
protected <T> T mapFromJson(String json, Class<T>
clazz)
throws JsonParseException, JsonMappingException,
IOException {
Next, write a class file that extends the AbstractTest class and
write a Unit Test for each method such GET, POST, PUT and
DELETE.
The code for GET API Test case is given below. This API is to view
the list of products.
@Test
public void getProductsList() throws Exception {
String uri = "/products";
MvcResult mvcResult =
mvc.perform(MockMvcRequestBuilders.get(uri)
.accept(MediaType.APPLICATION_JSON_VALUE)).andRet
urn();
The code for POST API test case is given below. This API is to
create a product.
@Test
public void createProduct() throws Exception {
String uri = "/products";
Product product = new Product();
product.setId("3");
product.setName("Ginger");
The code for PUT API Test case is given below. This API is to
update the existing product.
@Test
public void updateProduct() throws Exception {
String uri = "/products/2";
Product product = new Product();
product.setName("Lemon");
The code for Delete API Test case is given below. This API will
delete the existing product.
@Test
public void deleteProduct() throws Exception {
String uri = "/products/2";
MvcResult mvcResult =
mvc.perform(MockMvcRequestBuilders.delete(uri)).andRetu
rn();
int status = mvcResult.getResponse().getStatus();
assertEquals(200, status);
String content =
mvcResult.getResponse().getContentAsString();
assertEquals(content, "Product is deleted
successsfully");
}
package com.tutorialspoint.demo;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MvcResult;
import
org.springframework.test.web.servlet.request.MockMvcReq
uestBuilders;
import com.tutorialspoint.demo.model.Product;
public class ProductServiceControllerTest extends
AbstractTest {
@Override
@Before
public void setUp() {
super.setUp();
}
@Test
public void getProductsList() throws Exception {
String uri = "/products";
MvcResult mvcResult =
mvc.perform(MockMvcRequestBuilders.get(uri)
.accept(MediaType.APPLICATION_JSON_VALUE)).and
Return();
You can create an executable JAR file, and run the Spring Boot
application by using the Maven or Gradle commands given below
−
You can see the rest results in console window as shown below.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
Connect to H2 database
To connect the H2 database, we need to add the H2 database
dependency in our build configuration file.
For Maven users, add the below dependency in your pom.xml file.
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
compile('com.h2database:h2')
We need to create the schema.sql file and data.sql file under the
classpath src/main/resources directory to connect the H2
database.
Connect MySQL
To connect the MySQL database, we need to add the MySQL
dependency into our build configuration file.
compile('mysql:mysql-connector-java')
spring.datasource.driverClassName =
com.mysql.jdbc.Driver
spring.datasource.url =
jdbc:mysql://localhost:3306/PRODUCTSERVICE?
autoreconnect = true
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.testOnBorrow = true
spring.datasource.testWhileIdle = true
spring.datasource.timeBetweenEvictionRunsMillis = 60000
spring.datasource.minEvictableIdleTimeMillis = 30000
spring.datasource.validationQuery = SELECT 1
spring.datasource.max-active = 15
spring.datasource.max-idle = 10
spring.datasource.max-wait = 8000
spring:
datasource:
driverClassName: com.mysql.jdbc.Driver
url: "jdbc:mysql://localhost:3306/PRODUCTSERVICE?
autoreconnect=true"
username: "root"
password: "root"
testOnBorrow: true
testWhileIdle: true
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 30000
validationQuery: SELECT 1
max-active: 15
max-idle: 10
max-wait: 8000
Connect Redis
Redis is an open source database used to store the in-memory
data structure. To connect the Redis database in Spring Boot
application, we need to add the Redis dependency in our build
configuration file.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
compile('org.springframework.boot:spring-boot-starter-data-redis')
@Bean
JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory jedisConFactory = new
JedisConnectionFactory();
jedisConFactory.setHostName("localhost");
jedisConFactory.setPort(6000);
jedisConFactory.setUsePool(true);
return jedisConFactory;
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new
RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory())
;
template.setKeySerializer(new
StringRedisSerializer());
template.setHashKeySerializer(new
StringRedisSerializer());
template.setHashValueSerializer(new
StringRedisSerializer());
template.setValueSerializer(new
StringRedisSerializer());
return template;
}
Now auto wire the RedisTemplate class and access the data from
Redis database.
@Autowired
JDBCTemplate
To access the Relational Database by using JdbcTemplate in
Spring Boot application, we need to add the Spring Boot Starter
JDBC dependency in our build configuration file.
@Autowired
JdbcTemplate jdbcTemplate;
Collection<Map<String, Object>> rows =
jdbc.queryForList("SELECT QUERY");
@Repository
public class ProductServiceDAO {
}
Multiple DataSource
We can keep ‘n’ number Datasources in a single Spring Boot
application. The example given here shows how to create more
than 1 data source in Spring Boot application. Now, add the two
data source configuration details in the application properties file.
For properties file users, add the following properties into your
application.properties file.
spring.dbProductService.driverClassName =
com.mysql.jdbc.Driver
spring.dbProductService.url =
jdbc:mysql://localhost:3306/PRODUCTSERVICE?
autoreconnect = true
spring.dbProductService.username = root
spring.dbProductService.password = root
spring.dbProductService.testOnBorrow = true
spring.dbProductService.testWhileIdle = true
spring.dbProductService.timeBetweenEvictionRunsMillis =
60000
spring.dbProductService.minEvictableIdleTimeMillis =
30000
spring.dbProductService.validationQuery = SELECT 1
spring.dbProductService.max-active = 15
spring.dbProductService.max-idle = 10
spring.dbProductService.max-wait = 8000
spring.dbUserService.driverClassName =
com.mysql.jdbc.Driver
spring.dbUserService.url =
jdbc:mysql://localhost:3306/USERSERVICE?autoreconnect =
true
spring.dbUserService.username = root
spring.dbUserService.password = root
spring.dbUserService.testOnBorrow = true
spring.dbUserService.testWhileIdle = true
spring.dbUserService.timeBetweenEvictionRunsMillis =
60000
spring.dbUserService.minEvictableIdleTimeMillis = 30000
spring.dbUserService.validationQuery = SELECT 1
spring.dbUserService.max-active = 15
spring.dbUserService.max-idle = 10
spring.dbUserService.max-wait = 8000
spring:
dbProductService:
driverClassName: com.mysql.jdbc.Driver
url: "jdbc:mysql://localhost:3306/PRODUCTSERVICE?
autoreconnect=true"
password: "root"
username: "root"
testOnBorrow: true
testWhileIdle: true
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 30000
validationQuery: SELECT 1
max-active: 15
max-idle: 10
max-wait: 8000
dbUserService:
driverClassName: com.mysql.jdbc.Driver
url: "jdbc:mysql://localhost:3306/USERSERVICE?
autoreconnect=true"
password: "root"
username: "root"
testOnBorrow: true
testWhileIdle: true
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 30000
validationQuery: SELECT 1
max-active: 15
max-idle: 10
max-wait: 8000
import javax.sql.DataSource;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.beans.factory.annotation.Qualifier;
import
org.springframework.boot.autoconfigure.jdbc.DataSourceB
uilder;
import
org.springframework.boot.context.properties.Configurati
onProperties;
import org.springframework.context.annotation.Bean;
import
org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
@Configuration
public class DatabaseConfig {
@Bean(name = "dbProductService")
@ConfigurationProperties(prefix =
"spring.dbProductService")
@Primary
public DataSource createProductServiceDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "dbUserService")
@ConfigurationProperties(prefix =
"spring.dbUserService")
public DataSource createUserServiceDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "jdbcProductService")
@Autowired
public JdbcTemplate
createJdbcTemplate_ProductService(@Qualifier("dbProduct
Service") DataSource productServiceDS) {
return new JdbcTemplate(productServiceDS);
}
@Bean(name = "jdbcUserService")
@Autowired
public JdbcTemplate
createJdbcTemplate_UserService(@Qualifier("dbUserServic
e") DataSource userServiceDS) {
return new JdbcTemplate(userServiceDS);
}
}
@Qualifier("jdbcProductService")
@Autowired
JdbcTemplate jdbcTemplate;
@Qualifier("jdbcUserService")
@Autowired
JdbcTemplate jdbcTemplate;
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
compile("org.springframework.boot:spring-boot-starter-security")
<head>
<title>Spring Security Example</title>
</head>
<body>
<h1>Welcome!</h1>
<p>Click <a th:href = "@{/hello}">here</a> to see
a greeting.</p>
</body>
</html>
<!DOCTYPE html>
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:th = "http://www.thymeleaf.org"
xmlns:sec = "http://www.thymeleaf.org/thymeleaf-
extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello world!</h1>
</body>
</html>
Now, we need to setup the Spring MVC – View controller for home
and hello views.
import
org.springframework.context.annotation.Configuration;
import
org.springframework.web.servlet.config.annotation.ViewC
ontrollerRegistry;
import
org.springframework.web.servlet.config.annotation.WebMv
cConfigurerAdapter;
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter
{
@Override
public void
addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("home")
;
registry.addViewController("/").setViewName("home");
registry.addViewController("/hello").setViewName("hello
");
registry.addViewController("/login").setViewName("login
");
}
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Gradle users can add the following dependency in the build.gradle
file.
compile("org.springframework.boot:spring-boot-starter-security")
package com.tutorialspoint.websecuritydemo;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.context.annotation.Configuration;
import
org.springframework.security.config.annotation.authenti
cation.builders.AuthenticationManagerBuilder;
import
org.springframework.security.config.annotation.web.buil
ders.HttpSecurity;
import
org.springframework.security.config.annotation.web.conf
iguration.WebSecurityConfigurerAdapter;
import
org.springframework.security.config.annotation.web.conf
iguration.EnableWebSecurity;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws
Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void
configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("
USER");
}
}
<!DOCTYPE html>
<html xmlns = "http://www.w3.org/1999/xhtml" xmlns:th =
"http://www.thymeleaf.org"
xmlns:sec = "http://www.thymeleaf.org/thymeleaf-
extras-springsecurity3">
<head>
<title>Spring Security Example </title>
</head>
<body>
<div th:if = "${param.error}">
Invalid username and password.
</div>
<div th:if = "${param.logout}">
You have been logged out.
</div>
</body>
</html>
<!DOCTYPE html>
<html xmlns = "http://www.w3.org/1999/xhtml" xmlns:th =
"http://www.thymeleaf.org"
xmlns:sec = "http://www.thymeleaf.org/thymeleaf-
extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1 th:inline = "text">Hello [[$
{#httpServletRequest.remoteUser}]]!</h1>
<form th:action = "@{/logout}" method = "post">
<input type = "submit" value = "Sign Out"/>
</form>
</body>
</html>
package com.tutorialspoint.websecuritydemo;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
@SpringBootApplication
public class WebsecurityDemoApplication {
public static void main(String[] args) {
SpringApplication.run(WebsecurityDemoApplication.class,
args);
}
}
Maven – pom.xml
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>websecurity-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>websecurity-demo</name>
<description>Demo project for Spring
Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from
repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<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>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-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 – build.gradle
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-
starter-security')
compile('org.springframework.boot:spring-boot-
starter-thymeleaf')
compile('org.springframework.boot:spring-boot-
starter-web')
testCompile('org.springframework.boot:spring-boot-
starter-test')
testCompile('org.springframework.security:spring-
security-test')
}
Now, create an executable JAR file, and run the Spring Boot
application by using the following Maven or Gradle commands.
After “BUILD SUCCESS”, you can find the JAR file under target
directory.
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
Now, run the JAR file by using the command shown below −
Authorization Server
Authorization Server is a supreme architectural component for
Web API Security. The Authorization Server acts a centralization
authorization point that allows your apps and HTTP endpoints to
identify the features of your application.
Resource Server
Resource Server is an application that provides the access token
to the clients to access the Resource Server HTTP Endpoints. It is
collection of libraries which contains the HTTP Endpoints, static
resources, and Dynamic web pages.
OAuth2
OAuth2 is an authorization framework that enables the
application Web Security to access the resources from the client.
To build an OAuth2 application, we need to focus on the Grant
Type (Authorization code), Client ID and Client secret.
JWT Token
JWT Token is a JSON Web Token, used to represent the claims
secured between two parties. You can learn more about the JWT
token at www.jwt.io/.
You can use the following steps to implement the Spring Boot
Security with JWT token by accessing the database.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
compile('org.springframework.boot:spring-boot-starter-
security')
compile('org.springframework.boot:spring-boot-starter-
web')
testCompile('org.springframework.boot:spring-boot-
starter-test')
testCompile('org.springframework.security:spring-
security-test')
compile("org.springframework.security.oauth:spring-
security-oauth2")
compile('org.springframework.security:spring-security-
jwt')
compile("org.springframework.boot:spring-boot-starter-
jdbc")
compile("com.h2database:h2:1.4.191")
where,
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>websecurityapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>websecurityapp</name>
<description>Demo project for Spring
Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath /> <!-- lookup parent from
repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sour
ceEncoding>
<project.reporting.outputEncoding>UTF-8</project.report
ing.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-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 – build.gradle
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-
starter-security')
compile('org.springframework.boot:spring-boot-
starter-web')
testCompile('org.springframework.boot:spring-boot-
starter-test')
testCompile('org.springframework.security:spring-
security-test')
compile("org.springframework.security.oauth:spring-
security-oauth2")
compile('org.springframework.security:spring-
security-jwt')
compile("org.springframework.boot:spring-boot-
starter-jdbc")
compile("com.h2database:h2:1.4.191")
}
Also, you can use the following code to write a simple HTTP
endpoint to access the API with Spring Security by using JWT
Token.
package com.tutorialspoint.websecurityapp;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import
org.springframework.security.oauth2.config.annotation.w
eb.configuration.EnableAuthorizationServer;
import
org.springframework.security.oauth2.config.annotation.w
eb.configuration.EnableResourceServer;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableAuthorizationServer
@EnableResourceServer
@RestController
public class WebsecurityappApplication {
public static void main(String[] args) {
SpringApplication.run(WebsecurityappApplication.class,
args);
}
@RequestMapping(value = "/products")
public String getProductName() {
return "Honey";
}
}
Use the following code to define the POJO class to store the User
information for authentication.
package com.tutorialspoint.websecurityapp;
import java.util.ArrayList;
import java.util.Collection;
import
org.springframework.security.core.GrantedAuthority;
Now, use the following code and define the CustomUser class that
extends the org.springframework.security.core.userdetails.User
class for Spring Boot authentication.
package com.tutorialspoint.websecurityapp;
import
org.springframework.security.core.userdetails.User;
package com.tutorialspoint.websecurityapp;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import
org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import
org.springframework.security.core.GrantedAuthority;
import
org.springframework.security.core.authority.SimpleGrant
edAuthority;
import org.springframework.stereotype.Repository;
@Repository
public class OAuthDao {
@Autowired
private JdbcTemplate jdbcTemplate;
list.get(0).setGrantedAuthoritiesList(grantedAuthoritie
sList);
return list.get(0);
}
return null;
}
}
You can create a Custom User detail service class that extends
the
org.springframework.security.core.userdetails.UserDetailsService
to call the DAO repository class as shown.
package com.tutorialspoint.websecurityapp;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.security.core.userdetails.UserDetai
lsService;
import
org.springframework.security.core.userdetails.UsernameN
otFoundException;
import org.springframework.stereotype.Service;
@Service
public class CustomDetailsService implements
UserDetailsService {
@Autowired
OAuthDao oauthDao;
@Override
public CustomUser loadUserByUsername(final String
username) throws UsernameNotFoundException {
UserEntity userEntity = null;
try {
userEntity =
oauthDao.getUserDetails(username);
CustomUser customUser = new
CustomUser(userEntity);
return customUser;
} catch (Exception e) {
e.printStackTrace();
throw new UsernameNotFoundException("User " +
username + " was not found in the database");
}
}
}
package com.tutorialspoint.websecurityapp;
import
org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import
org.springframework.context.annotation.Configuration;
import
org.springframework.security.authentication.Authenticat
ionManager;
import
org.springframework.security.config.annotation.authenti
cation.builders.AuthenticationManagerBuilder;
import
org.springframework.security.config.annotation.method.c
onfiguration.EnableGlobalMethodSecurity;
import
org.springframework.security.config.annotation.web.buil
ders.HttpSecurity;
import
org.springframework.security.config.annotation.web.buil
ders.WebSecurity;
import
org.springframework.security.config.annotation.web.conf
iguration.EnableWebSecurity;
import
org.springframework.security.config.annotation.web.conf
iguration.WebSecurityConfigurerAdapter;
import
org.springframework.security.config.http.SessionCreatio
nPolicy;
import
org.springframework.security.crypto.bcrypt.BCryptPasswo
rdEncoder;
import
org.springframework.security.crypto.password.PasswordEn
coder;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends
WebSecurityConfigurerAdapter {
@Autowired
private CustomDetailsService customDetailsService;
@Bean
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
@Override
@Autowired
protected void
configure(AuthenticationManagerBuilder auth) throws
Exception {
auth.userDetailsService(customDetailsService).passwordE
ncoder(encoder());
}
@Override
protected void configure(HttpSecurity http) throws
Exception {
http.authorizeRequests().anyRequest().authenticated().a
nd().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.N
EVER);
}
@Override
public void configure(WebSecurity web) throws
Exception {
web.ignoring();
}
@Override
@Bean
public AuthenticationManager
authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
Now, define the OAuth2 Configuration class to add the Client ID,
Client Secret, Define the JwtAccessTokenConverter, Private key
and Public key for token signer key and verifier key, and configure
the ClientDetailsServiceConfigurer for the Token validity with
scopes.
package com.tutorialspoint.websecurityapp;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import
org.springframework.context.annotation.Configuration;
import
org.springframework.security.authentication.Authenticat
ionManager;
import
org.springframework.security.oauth2.config.annotation.c
onfigurers.ClientDetailsServiceConfigurer;
import
org.springframework.security.oauth2.config.annotation.w
eb.configuration.AuthorizationServerConfigurerAdapter;
import
org.springframework.security.oauth2.config.annotation.w
eb.configurers.AuthorizationServerEndpointsConfigurer;
import
org.springframework.security.oauth2.config.annotation.w
eb.configurers.AuthorizationServerSecurityConfigurer;
import
org.springframework.security.oauth2.provider.token.stor
e.JwtAccessTokenConverter;
import
org.springframework.security.oauth2.provider.token.stor
e.JwtTokenStore;
@Configuration
public class OAuth2Config extends
AuthorizationServerConfigurerAdapter {
private String clientid = "tutorialspoint";
private String clientSecret = "my-secret-key";
private String privateKey = "private key";
private String publicKey = "public key";
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Bean
public JwtAccessTokenConverter tokenEnhancer() {
JwtAccessTokenConverter converter = new
JwtAccessTokenConverter();
converter.setSigningKey(privateKey);
converter.setVerifierKey(publicKey);
return converter;
}
@Bean
public JwtTokenStore tokenStore() {
return new JwtTokenStore(tokenEnhancer());
}
@Override
public void
configure(AuthorizationServerEndpointsConfigurer
endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager).
tokenStore(tokenStore())
.accessTokenConverter(tokenEnhancer());
}
@Override
public void
configure(AuthorizationServerSecurityConfigurer
security) throws Exception {
security.tokenKeyAccess("permitAll()").checkTokenAccess
("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer
clients) throws Exception {
clients.inMemory().withClient(clientid).secret(clientSe
cret).scopes("read", "write")
.authorizedGrantTypes("password",
"refresh_token").accessTokenValiditySeconds(20000)
.refreshTokenValiditySeconds(20000);
}
}
You can use the following commands for generating private key.
You can use For public key generation use the below commands.
For the version of Spring Boot latter than 1.5 release, add the
below property in your application.properties file to define OAuth2
Resource filter order.
security.oauth2.resource.filter-order=3
YAML file users can add the below property in YAML file.
security:
oauth2:
resource:
filter-order: 3
You can create an executable JAR file, and run the Spring Boot
application by using the following Maven or Gradle commands.
After “BUILD SUCCESS”, you can find the JAR file under the target
directory.
Now, run the JAR file by using the command shown here −
Now hit the POST method URL via POSTMAN to get the OAUTH2
token.
http://localhost:8080/oauth/token
grant_type = password
username = your username
password = your password
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
classpath 'com.google.cloud.tools:appengine-
gradle-plugin:1.3.3'
}
}
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')
}
package com.tutorialspoint.appenginedemo;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class AppengineDemoApplication {
public static void main(String[] args) {
SpringApplication.run(AppengineDemoApplication.class,
args);
}
@RequestMapping(value = "/")
public String success() {
return "APP Engine deployment success";
}
}
runtime: java
env: flex
handlers:
- url: /.*
script: this field is required, but ignored
Now, move your source files and Gradle file into home directory of
your google cloud machine by using google cloud shell.
jdbc:mysql://google/<DATABASE-NAME>?cloudSqlInstance =
<GOOGLE_CLOUD_SQL_INSTANCE_NAME> &socketFactory =
com.google.cloud.sql.mysql.SocketFactory&user = <USERNAME>&password
= <PASSWORD>
Note − The Spring Boot application and Google Cloud SQL should
be in same GCP project.
spring.dbProductService.driverClassName =
com.mysql.jdbc.Driver
spring.dbProductService.url =
jdbc:mysql://google/PRODUCTSERVICE?cloudSqlInstance =
springboot-gcp-cloudsql:asia-northeast1:springboot-gcp-
cloudsql-instance&socketFactory =
com.google.cloud.sql.mysql.SocketFactory&user =
root&password = rootspring.dbProductService.username =
root
spring.dbProductService.password = root
spring.dbProductService.testOnBorrow = true
spring.dbProductService.testWhileIdle = true
spring.dbProductService.timeBetweenEvictionRunsMillis =
60000
spring.dbProductService.minEvictableIdleTimeMillis =
30000
spring.dbProductService.validationQuery = SELECT 1
spring.dbProductService.max-active = 15
spring.dbProductService.max-idle = 10
spring.dbProductService.max-wait = 8000
spring:
datasource:
driverClassName: com.mysql.jdbc.Driver
url: "jdbc:mysql://google/PRODUCTSERVICE?
cloudSqlInstance=springboot-gcp-cloudsql:asia-
northeast1:springboot-gcp-cloudsql-
instance&socketFactory=com.google.cloud.sql.mysql.Socke
tFactory&user=root&password=root"
password: "root"
username: "root"
testOnBorrow: true
testWhileIdle: true
validationQuery: SELECT 1
max-active: 15
max-idle: 10
max-wait: 8000
buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-
gradle-plugin:${springBootVersion}")
}
}
group = 'com.tutorialspoint.projects'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-
starter')
testCompile('org.springframework.boot:spring-boot-
starter-test')
compile('org.springframework.security.oauth:spring-
security-oauth2')
compile('org.springframework.boot:spring-boot-
starter-web')
testCompile('org.springframework.boot:spring-boot-
starter-test')
}
Now, add the HTTP Endpoint to read the User Principal from the
Google after authenticating via Spring Boot in main Spring Boot
application class file as given below −
package com.tutorialspoint.projects.googleservice;
import java.security.Principal;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplic
ation;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class GoogleserviceApplication {
public static void main(String[] args) {
SpringApplication.run(GoogleserviceApplication.class,
args);
}
@RequestMapping(value = "/user")
public Principal user(Principal principal) {
return principal;
}
}
package com.tutorialspoint.projects.googleservice;
import
org.springframework.boot.autoconfigure.security.oauth2.
client.EnableOAuth2Sso;
import
org.springframework.context.annotation.Configuration;
import
org.springframework.security.config.annotation.web.buil
ders.HttpSecurity;
import
org.springframework.security.config.annotation.web.conf
iguration.WebSecurityConfigurerAdapter;
@Configuration
@EnableOAuth2Sso
public class WebSecurityConfiguration extends
WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws
Exception {
http
.csrf()
.disable()
.antMatcher("/**")
.authorizeRequests()
.antMatchers("/", "/index.html")
.permitAll()
.anyRequest()
.authenticated();
}
}
Next, add the index.html file under static resources and add the
link to redirect into user HTTP Endpoint to read the Google user
Principal as shown below −
<!DOCTYPE html>
<html>
<head>
<meta charset = "ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href = "user">Click here to Google Login</a>
</body>
</html>
Note − In Google Cloud console - Enable the Gmail Services,
Analytics Services and Google+ service API(s).
security.oauth2.client.clientId = <CLIENT_ID>
security.oauth2.client.clientSecret = <CLIENT_SECRET>
security.oauth2.client.accessTokenUri =
https://www.googleapis.com/oauth2/v3/token
security.oauth2.client.userAuthorizationUri =
https://accounts.google.com/o/oauth2/auth
security.oauth2.client.tokenName = oauth_token
security.oauth2.client.authenticationScheme = query
security.oauth2.client.clientAuthenticationScheme =
form
security.oauth2.client.scope = profile email
security.oauth2.resource.userInfoUri =
https://www.googleapis.com/userinfo/v2/me
security.oauth2.resource.preferTokenInfo = false
Now, you can create an executable JAR file, and run the Spring
Boot application by using the following Gradle command.
After “BUILD SUCCESSFUL”, you can find the JAR file under the
build/libs directory.
Run the JAR file by using the command java –jar <JARFILE> and
application is started on the Tomcat port 8080.