Developing REST Service using Spring Boot
Overview
In this tutorial we’ll learn, how to develop a REST API using Spring Boot framework.
We’ll primarily use Java configuration in this tutorial.
Pre-requisties
- JDK 1.8
- Maven
- IDE (for ease of use)
Setup maven project
Creat a maven project and add the required dependencies and plugins in pom.xml
We will use the dependencyManagement to define a standard version of an artifact to use across multiple projects.
We will allow spring-boot-starter-parent to manage the version of the artifacts.
1 | <dependencyManagement> |
Now we’ll add the spring-boot-starter-web dependency.
Spring Boot Starter Web includes:
- spring-web module
- spring-webmvc module
- tomcat starter
Spring-web & Spring-webmvc are required for spring appplication while tomcat starter is required to run web application directly without explicitly installing any server.
1 | <dependencies> |
Spring Boot Maven Plugin provides Spring Boot support in Maven, letting you package executable jar or war archives and run an application “in-place”.
1 | <build> |
Creating a Spring Boot Application
Create a class with main method. Annotate the class with @SpringBootApplication. Call the run method of SpringApplication class
1 | package com.tutorialflix.spring.web; |
@SpringBootApplication includes the functionality of following annotations:
- @Configuration
- @EnableAutoConfiguration
- @ComponentScan.
** By default, it will perform the component scan in base package. So make sure SpringBootWebApplication class is present in the base package.**
Creating a REST Controller
Create a class with a meaningful name based on your requirement & annotate the class with @RestController. The @RestController is the central artifact in the entire Web Tier of the RESTful API.
1 | package com.tutorialflix.spring.web.contrroller; |
Create a GET method to accept requests
Create a method named home to accept the request on ‘/‘ url and show the index.html
1 |
|
Create a POST method to accept requests
Create a method named home to accept the request on ‘/‘ url and show the index.html
1 |
|
Configuration using properties file
Create a file application.properties inside resources folder of application and following properties.
1 | server.port=8081 |
server.port : to change the default port 8080 to any other port number.
logging.level.org.springframework.web : to change the log level default INFO to DEBUG
Run the REST API
1 | $ mvn spring-boot:run |
Test
Developing REST Service using Spring Boot
https://tutorialflix.com/Developing-REST-Service-using-Spring-Boot/