Tuesday, May 2, 2017

How to Develop Microservices with Spring Boot

Spring Boot is a good framework/platform for Java to develop microservices. Other programming languages also have frameworks that enable writing microservices with easy: Python with Flask, PHP with Laravel Lumen. With Java platform you also have many options: Spring Boot is one, but there is also Dropwizard, Vert.x, and Play framework (nice if you like Scala).

It is also possible to develop a microservice application from scratch using a plain Maven project, since you can add POM dependencies easily. However, you will soon be busy wiring and configuring several low-level infrastructural things like logging, HTTP client library, security, and so on that it may distract you from the core issue: application functionality.

Advantages of Spring Boot for Microservices

There are a number of advantages of using Spring Boot for developing microservices. This is not all but you get the idea.

  • You get necessary infrastructural "services" like logging, application configuration, REST API support (both client and server), JSON parsing and generation, data access, mostly out-of-the-box or with minimal configuration.
  • Spring Boot application is directly runnable. Once the app is built with Maven, it can be run using "java -jar" standard technique, and it can be deployed on any server (just by installing a JRE or JDK) or cloud platforms such as Cloud Foundry, Red Hat OpenShift, Heroku, and so on.
  • Lightweight footprint. While the definition of "lightweight" can be ambiguous (a Spring Boot application isn't as light as a bare bones Java app without logging etc.), a minimal Spring Boot app has only a few dependencies. In practice it's just Spring Framework dependency injection, logging, Spring Boot thin wrapper, and some helper libraries that are useful for your app as well. You can add only Spring Boot modules that you need so there is no unnecessary bloat. It keeps memory usage minimum as well.
  • Fast. A simple Spring Boot app starts in a few seconds. Less startup time means it can get your app to do its job sooner.
  • Modular. There are various Spring Boot modules that provide additional functionality. Mostly minimal configuration and some doesn't even require any configuration. For example if you need a web server you can just add Spring Boot Web and you can access it at http://localhost:8080/ by default (using embedded Tomcat).
  • Flexible. Even though most modules require minimal or no configuration, it doesn't mean that you're restricted. It's still using the Spring programming model, which means pretty much everything is configure. I have to confess that I think sometimes it can get a bit difficult to locate where to find out how to do certain things. But fortunately, Spring Framework is not an unknown framework: it's a popular framework and I think millions of developers use it on a daily basis. There are already answers on StackOverflow and forums or blogs for most common cases.
  • Stable. Spring Boot is based on Spring Framework which is very stable and mature, yet still incorporates the latest advances and features in Java technology. However, Spring Boot is built on top of Spring, and has more moving parts, meaning that it's possible that it breaks considering that it has to integrate a lot of different modules. Yet it's even easier to break your own wiring of components in a "plain Spring" app because of component incompatibility or configuration. Each Spring Boot versions recommends a particular set of components, versions, and configurations, that are known to work together, so the chances of them breaking is fairly low. In a microservice app it is even better as there should be minimal dependencies, therefore Spring Boot is a good fit.
  • Support. Spring Boot uses popular open source components like Spring Framework, Hibernate, Tomcat, so there are free articles, StackOverflow answers, and books of these available. Paid support services are also available from Pivotal and Java consultants, including enterprise support for each of the open source components.
  • Secure. By adding Spring Security module, you get default security consisting of a "user" username and automatically generated password (viewable from the app console logs). After that you can configure specific security features like JDBC user/credentials store, HTTP security, etc.
  • Easy to deploy. As mentioned above, since Spring Boot app is just a Java JAR it can be deployed on any ordinary server (via file transfer such as SSH, FTP, SFTP) and then run using "java -jar". For managed services, it is recommended to deploy it on a PaaS cloud offering such as Pivotal Cloud Foundry, Red Hat OpenShift, Heroku, and so on. There is no lock-in as Spring Boot does not require a specific platform (other than Java). You can also build Spring Boot apps as WAR and deploy them on Tomcat servlet container.
  • It's "just Spring" underneath. While there are advantages/disadvantages of using non-Java platforms like Python, NodeJS, Go, etc., when you consider Java you also consider that a lot of server-side Java programmers know Spring. There are good reasons to use Vert.x and Play framework, but Spring programmers using Spring Boot will usually have better experience resolving issues.

How to Create a Microservices App with Spring Boot

1. First you need to create a Spring Boot web app

Make sure to include the Spring Web module, as you'll need it to serve your REST API endpoints. It is recommended to include Spring Security, as most microservice will require OAuth access token, JWS token, or some other form of authentication.

2. Add a @RestController class.

Here's a simple @RestController implementation that simply returns a POJO object.

package demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

public class OrderController {

    public static class Order {
        private String name;
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }

    public Order getOrder() {
        Order order = new Order();
        order.setName("Happy meal");

        return order;

A @RestController may contain several service methods. Each method usually for a single HTTP method mapping (@GetMapping, @PostMapping), and for a specific path (probably with path parameters).

3. Run the app and test your service method.

Run the app. You can test your service method by visiting the service URL using web browser, for example http://localhost:8080/order in the simple example above.

I prefer using Postman to test my service APIs, which has a convenient UI. You can experiment with different parameters, save HTTP requests into a collection, and display/edit HTTP request bodies and responses with pretty syntax highlight. You'll notice with HTTP requests that accept JSON (set header Accept: application/json), Spring Boot Web automatically converts the returned object to JSON representation.

The JSON support is provided by Jackson, which is automatically configured by Spring Boot for sane defaults. You can also configure Jackson to your liking, for example to pretty print JSON (not recommended for bandwidth), add Jackson support modules such as Joda time and so on.

Next Steps

There are several functionality that is needed in a microservice app, such as connecting to SQL databases, communicating via RESTful HTTP API with other (micro)services, and executing background operations. But I hope this short tutorial can get you started on microservices development using Spring Boot. Let me know if there are specific cases I can help you with.

To learn more about Spring Boot, I highly recommend Spring Boot in Action: