Overview

Spring boot is a rapid application development platform based on Spring framework. It reduces the need to write lots of configuration and boiler plate codes. It helps you to get you app up in minutes if not seconds. Below steps will help you to get a kick start with Spring Boot.

Getting Started

The best and easiest way to get started is using Spring Initializr. Goto : https://start.spring.io/

Select all the options and dependencies you want. Here I’m going to generate a simple Spring Boot App with Gradle as build tool. To start with, we just select the only required dependency for current project : Spring Web

Click Generate. It will download the source in zip format.

Import the project into IDE

Unzip and downloaded source code. The following screenshots shows how it is done in IntelliJ. The step are similar for Eclipse as well.

Open IntelliJ and select Import Project

Navigate to the unzipped folder and select

In the next screen, select project model as Gradle and click Finish

The project will be imported and IntelliJ should automatically download the dependencies.

The only dependency needed for now is available in build.gradle file

implementation 'org.springframework.boot:spring-boot-starter-web'

Starting the application

Right away, you can try to start the application by right clicking on SpringBootRestApplication and select Run

When you see the below message in console, you’ll know that the application is started

INFO 12180 --- [           main] c.l.s.SpringBootRestApplication          : Started SpringBootRestApplication in 1.976 seconds (JVM running for 2.427)

But this application doesn’t do anything. Lets add an API endpoint.

Adding API End Point

What we are trying here is to set up a very simple API that returns names of the planets. This post is aimed to have the Spring Boot Application up and running with an exposed API.

Add a new package : com.logicalsapien.springbootrest.controller

and class : com.logicalsapien.springbootrest.controller.PlanetController

with following code:

PlanetController.java

package com.logicalsapien.springbootrest.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/planets")
public class PlanetController {

    /**
     * get Api to return list of all planets.
     * @return List of Planets
     */
    @GetMapping()
    public ResponseEntity<List<String>> listAllPlanets() {
        List<String> planetList
                = List.of("Mercury", "Venus", "Earth", "Mars",
                            "Jupiter", "Saturn", "Uranus", "Neptune");
        return new ResponseEntity<>(planetList, HttpStatus.OK);
    }
}

Then stop and start the Application Again.

Now go to browser, or any REST client to verify the application :

Hurrah!! we have the response from API.

Points to note

  • @SpringBootApplication will mark tells Spring that its a Spring Boot Application and take care of all configuration. Its replaces a number of annotation such as @Configuration, @EnableAutoConfiguration etc.
  • We have used @RestController to mark the class as Rest Controller .
  • @RequestMapping("/planets") told Spring to get any request with the path ‘/planets’ to this controller.
  • @GetMapping() told spring to route the default Get request to the PlanetController to listAllPlanets() method.

Build & Run the Application via Gradle

To build it using Gradle, navigate to the source folder in Terminal/Command-Line, and enter below command:

./gradlew clean build

or

gradlew clean build

You should get below output:

BUILD SUCCESSFUL in 7s<br>
4 actionable tasks: 4 executed

To run the application please type in: (make sure that the application running in IntelliJ is stopped, otherwise you’ll get Port already in use error)

java -jar build/libs/spring-boot-rest-0.0.1-SNAPSHOT.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.0.RELEASE)

2019-10-17 09:03:39.032  INFO 12636 --- [           main] c.l.s.SpringBootRestApplication          : Starting SpringBootRestApplication on DESKTOP-AQQBP32 with PID 12636 (C:\Users\Owner\Documents\Workspace\spring-demos\spring-boot-rest\build\libs\spring-boot-rest-0.0.1-SNAPSHOT.jar started by Owner in C:\Users\Owner\Documents\Workspace\spring-demos\spring-boot-rest)
2019-10-17 09:03:39.036  INFO 12636 --- [           main] c.l.s.SpringBootRestApplication          : No active profile set, falling back to default profiles: default
2019-10-17 09:03:40.173  INFO 12636 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-10-17 09:03:40.183  INFO 12636 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-10-17 09:03:40.183  INFO 12636 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.27]
2019-10-17 09:03:40.242  INFO 12636 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-10-17 09:03:40.242  INFO 12636 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1143 ms
2019-10-17 09:03:40.404  INFO 12636 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-10-17 09:03:40.576  INFO 12636 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-10-17 09:03:40.580  INFO 12636 --- [           main] c.l.s.SpringBootRestApplication          : Started SpringBootRestApplication in 1.978 seconds (JVM running for 2.374)

That will start the server and you can call the API from browser or REST client as we did earlier. To stop it in – Ctrl + C

Conclusion

We set up a very basic application to test the Spring Boot features. This will help you to get started.

Additional Readings

Notes

View the full code in GitHub

CI Build on Travis

Code quality on Sonar Cloud