James Schmidt

Senior Software Engineer at InMoment

Follow me on GitHub

Creating an Application with Spring Boot

on spring

Spring Boot

Spring Boot is a framework for building applications and managing depedencies. The Spring team determines which versions of libraries work well together and makes that available in a nice package. Spring Boot is what I reach for to get a Java-based microservice up and running quickly.

Getting Started

To get started go to Spring Initializr. Add the Web dependency and generate the project. Unzip the downloaded folder.

Hello World

Now add an HTTP endpoint to the application. Edit the demo/src/main/java/com/example/DemoApplication.java in the unzipped folder you just downloaded. Add the imports for RestController and RequestMapping. Add the @RestController annotation to the class. Add the index method with the @RequestMapping annotation.

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

@SpringBootApplication
@RestController
public class DemoApplication {

  @RequestMapping("/")
  public String index() {
    return "hello world";
  }

  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
}

Run the Application

Open a shell and navigate to the unzipped folder and start the Spring Boot service.

$ mvn spring-boot:run

Now open another shell and send a request to the service.

$ curl localhost:8080

You can also open a browser and navigate to localhost:8080. You are done. Congratulations!

Room for Improvement

  • I usually like to rename the application class in the project to Application. This also means renaming the generated application test class too.
  • Keeping with the Single Responsibility Principle (SRP), it is best to have a separate controller class(es) for handling HTTP requests.
  • Editing and running Spring Boot applications is easier using Spring Tool Suite.
  • The team updates Spring Boot often so I find using Spring Initializr easier than their CLI tool or STS integration.

The repo can be found at https://github.com/jamesdschmidt/hello-spring-boot.