In this spring boot quick start, we will learn how to create a spring application using Spring Initializr. In this article, we will create a spring boot project and import it in any editor like eclipse or sts, then create a rest controller and use @GetMapping for creating spring boot rest API example.
When you have completed this tutorial, you should understand:
Spring Boot is built on top of the spring framework. So, it provides all the features of spring. Spring Boot is a microservice-based framework and makes a production-ready application in very little time. In Spring Boot, everything is auto-configured. It allows us to build a stand-alone application with minimal or zero configurations. It is better to use if we want to develop a simple Spring-based application or RESTful services.
Now we will see how to create a Spring Boot project using Spring Initializr. For this, you go to https://start.spring.io/ website and fill in the simple details like group, artifact, and dependencies as per your need.
After filling in these data you should click on generate project button; it will generate the spring boot project and download it as a zip for you. Now you can just unzip this project and import any IDE.
After importing this spring boot application, you create HelloController.java class as below. This is the REST controller in the Spring Boot application. Now we will create a Spring Boot RESTful web services JSON example.
We map your request in HellpController.java class with the help of @GetMapping annotation.
package com.jp.helloWorld.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.jp.helloWorld.model.User;
@RestController
public class HelloController {
@GetMapping("/user")
public User getApplicationName(){
User user = new User( 10L, "amit");
return user;
}
}
Create one POJO class User.java
package com.jp.helloWorld.model;
public class User {
private Long userId;
private String name;
public User(){
}
public User(Long userId, String name) {
super();
this.userId = userId;
this.name = name;
}
public Long getUserId() {
return userId;
}
public String getName() {
return name;
}
}
Now when you run the spring boot application from the main class as a spring boot application, it will run on the 8080 port by default. You can change the default port of the spring boot application during configuration in the application.
When you call our Spring Boot REST API using url http://localhost:8080/user with get method, then you will get:
{"userId":10,"name":"amit"}
I hope I have shared enough information which is helpful for beginners in developing a Spring Boot REST API example.