archive2015

A small REST service with Spring Boot 1.2 and Java 8

The Spring Boot 1.2 setup I start small JSON APIs from: Maven, @SpringBootApplication, a controller with validation, configuration, Actuator health checks, and running it as a service.

5 min read#dev#java#spring-boot

I had to start a small internal JSON API this month and copied the setup from an older project. Half of it was no longer needed with Spring Boot 1.2, so I cleaned it up and am keeping the clean version here.

Spring Boot starts a Spring web service from one main method with an embedded Tomcat. No WAR file and no external application server. Version 1.2.0 came out in December 2014 and added @SpringBootApplication. The current version is 1.2.2.

It fits a JSON API or small web app in Java, with a database or queue behind it, in a team that already knows Spring. It fits less well for a tiny tool where start time and memory matter: a Boot app needs a few seconds to start and some hundred MB of heap, which is slow on a Raspberry Pi 1. And if nobody on the team knows Spring, the auto-configuration is hard to debug when it does something unexpected.

Maven setup

<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.example</groupId>
    <artifactId>notes-api</artifactId>
    <version>0.1.0</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.2.RELEASE</version>
    </parent>

    <properties>
        <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-actuator</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>

The parent POM sets the versions of all Spring and library dependencies, so the starters have no version numbers. If you need a different version of one library, override its property (for example <jackson.version>) instead of adding a version to the dependency. Mixing your own Spring versions with Boot’s gives strange errors at start time.

Application class

package com.example.notes;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

@SpringBootApplication is @Configuration, @EnableAutoConfiguration and @ComponentScan together. Component scan starts in the package of this class, so put it in the root package (com.example.notes) and everything else in sub-packages. A controller outside the root package is not found, and you get a 404 with no error message. This one has cost me time more than once.

Model and controller

package com.example.notes.web;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class Note {
    private Long id;

    @NotNull
    @Size(min = 1, max = 200)
    private String text;

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getText() { return text; }
    public void setText(String text) { this.text = text; }
}
package com.example.notes.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import javax.validation.Valid;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/notes")
public class NoteController {

    private final Map<Long, Note> store = new ConcurrentHashMap<>();
    private final AtomicLong ids = new AtomicLong();

    @RequestMapping(method = RequestMethod.GET)
    public List<Note> list() {
        return new ArrayList<>(store.values());
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Note get(@PathVariable long id) {
        Note n = store.get(id);
        if (n == null) {
            throw new NotFoundException();
        }
        return n;
    }

    @RequestMapping(method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.CREATED)
    public Note create(@Valid @RequestBody Note note) {
        note.setId(ids.incrementAndGet());
        store.put(note.getId(), note);
        return note;
    }

    @ResponseStatus(HttpStatus.NOT_FOUND)
    static class NotFoundException extends RuntimeException {
    }
}

The in-memory map is only for the example; replace it with a repository class. @Valid checks the annotations on Note, and a bad request returns HTTP 400. Hibernate Validator comes with spring-boot-starter-web, so there is nothing to add.

An exception class with @ResponseStatus is the simplest way to return 404. For a bigger API I use one @ControllerAdvice class that maps all exceptions to status codes and one JSON error format.

Configuration

src/main/resources/application.properties:

server.port=8080
management.port=8081
management.address=127.0.0.1
spring.jackson.serialization.indent_output=true

management.port moves the Actuator endpoints (/health, /metrics, /env) to another port bound to localhost. They show internal data and should not be on the public port.

Every property can be overridden at start: java -jar app.jar --server.port=9000, or with an environment variable SERVER_PORT=9000. I use this for the differences between environments and build one JAR for all of them. Secrets like database passwords stay out of the JAR. Pass them as environment variables or in an external application.properties; Boot also reads ./application.properties and ./config/application.properties from the working directory.

Build, run, test

mvn clean package
java -jar target/notes-api-0.1.0.jar

curl -s -X POST -H 'Content-Type: application/json' \
  -d '{"text":"first note"}' http://localhost:8080/api/notes
curl -s http://localhost:8080/api/notes
curl -s http://127.0.0.1:8081/health

If something is configured that you did not ask for, start with --debug to print the auto-configuration report. For example, an H2 or HSQLDB JAR on the classpath gives you an in-memory DataSource.

Running it on a Linux server

The JAR contains everything (10 to 20 MB is normal; do not commit it). On the server you need a JRE 8 and something that starts the process at boot and restarts it on failure. On Ubuntu 14.04 an Upstart job is simple. /etc/init/notes-api.conf:

description "notes api"
start on runlevel [2345]
stop on runlevel [!2345]
respawn
setuid notes
chdir /opt/notes-api
exec /usr/bin/java -Xmx256m -jar /opt/notes-api/notes-api.jar

Then sudo start notes-api. Logs go to /var/log/upstart/notes-api.log unless you set logging.file.

Set -Xmx. Without it the JVM takes a share of the machine’s memory as its maximum heap, which can be too much on a server with other services.

Checklist for the next project

  • Parent POM 1.2.2.RELEASE, Java 1.8.
  • Application class in the root package.
  • Validation on input objects, clear status codes.
  • Actuator on a separate port bound to localhost.
  • Environment settings outside the JAR.
  • -Xmx set, process started by the init system.