Tag: Spring Boot

Spring Boot and WordPress CMS Integration



There are a lot of excellent open source content management systems available today,  WordPress being one of them, which is widely used. WordPress is a PHP based CMS so not a lot of cohesion is available with other technologies like Java, and is simply ignored as a viable content management option just for being non-Java.

In this post I will demonstrate how WordPress can be integrated with Spring Boot applications, all made possible with WordPress REST plugin and a Spring client. Both of these are open source and available for free. Below is a simple design diagram that explains how this integration works. This post assumes that the reader has prior knowledge of WordPress and Spring Boot.

First install and activate WP-API v2 plugin on the WordPress site. After activation, you could verify that the plugin is working by accessing http://yoursite/wp-json/wp/v2/posts, which should display all the posts in JSON format.In the spring boot application add the following dependency in order to include the Spring WP-API client.

Below is a sample configuration we need in the application.properties file, so that we can connect our Spring Boot application to our WordPress site.

The Spring WP-API client needs the RestTemplate so lets create a bean in our Application and autowire the Spring client. We also need to add component scan annotation so that Spring finds and autowires all the required dependencies.

Now our spring boot application is all setup to connect to out WordPress site in order to retrieve and create content. So lets try and lookup all the posts having the keyword “Spring”, below is how we can do this.

The complete test application is available with the Spring WP-API client on Github.

This is just a small example of how we can integrate Spring Boot and WordPress. We can take this further by properly integrating WordPress in the Spring web applications platform, e.g. by enabling Single Sign On using the CAS plugin.

And we can evolve this design even further by having a second-level content storage, like a database or an in-memory caching solution etc. This storage can serve as a cache and can also be used for additional configuration, so that we display relevant content faster in our Spring applications.

For more information please see the documentation of the WordPress REST plugin and Spring WP-API client.

How to Create Spring Boot Application Step by Step



How to Create Spring Boot Application Step by Step

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInPrint this pageShare on TumblrShare on Reddit

Spring Boot had been built for Rapid Application Development. In this tutorial we will learn How to Create Spring Boot Application using some easy examples. We will also focus on How to deploy spring boot application in different application servers.

Here are the following topics that we will cover in this series:

  1. Create Spring Boot Application using
    • start.spring.io
    • Eclipse STS
    • IntelliJ IDEA STS
  2. Run Spring Boot Application using
    • Java CLI
    • Eclipse/IntelliJ IDEA
  3. Create a Basic Spring Boot application using REST
  4. How to use Spring Actuator
  5. Deploy Spring Boot application in
    • IBM Liberty Profile
    • IBM Application Server 8.5

If you need an introduction of Spring Boot please find my previous post below.

Create Spring Boot Application using start.spring.io

The best way of bootstrapping Spring Boot application is by using Spring Initializr. Let’s first start by opening http//start.spring.io.As you already know, you can use either Maven or Gradle to build, however we will use Maven in this tutorial. Click on Switch to the full Version and you will be able to see the below screen.

Software Needed

  • JDK 1.8 (You can use 1.7 or 1.6)
  • Maven 3.x

Steps :

  • Select Maven Project
  • If you want, change the Group/Package name. We will use com.adeveloperdiary
  • Change the Artifact to SpringBoot, Name will automatically change to the same
  • Leave the packaging to Jar, Java Version to 1.8 (Make sure you have JDK 1.8 in your local or use 1.7 )
  • Either type the Dependencies or select them below. We will add Web and Actuator here
  • Click on Generate Project button to download the zip file

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Now Extract the zip and you will have the following files.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Open Terminal and navigate to the above folder. Type mvn clean packageand press enter. The Build will start now.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Once the build has been completed, you will have the SpringBoot-0.0.1-SNAPSHOT.jar created inside the target folder.

The Size of the jar would be around 13MB since it will have the embedded Tomcat server in it.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Create Spring Boot Application using Eclipse

We will use STS Toolkit to bootstrap when using eclipse. I am using eclipse MARS .1 version. We will first install the STS (SpringSource Tools Suite). Open Eclipse Marketplace, Type STS in Find and install the STS.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Then open Spring perspective.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Create a New -> Spring Starter Project.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Enter the following details. Click Next.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Select Web and Actuator. Click on Next.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Click on Finish.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

This should create the Spring Boot Project in Eclipse.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Create Spring Boot Application using IntelliJ IDEA

We will now use IntelliJ IDEA to create our Spring Boot Application.I recommend to use the latest version of IntelliJ. Create a New Project. Select Spring Initializr. Click on Next.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Enter the following details. Click Next.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Select Web and Actuator. Click Next.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Enter the project Name and click Finish.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Your Spring Boot Project has been created now.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Run Spring Boot Application using CLI

We had created the jar file, now we will run it from Command Line by executing this line

You should be able to see Spring Boot in the Command Line.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

The server should have started and the default port number will also be displayed as below.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Run Spring Boot Application in Eclipse

Its much easier to run the Spring Boot app in eclipse. Select the project, Right Click and, move to Run As and click on Spring Boot App. Again, remember you need to select the project to get this option, not the pom file.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Here is the output.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Run Spring Boot Application in IntelliJ IDEA

Its probably most easy, click on the run icon.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

You should be able to see the logs that the application has started.

How to Create Spring Boot Application Step by Step adeveloperdiary.com


Hope this Step by Step approach will help you. Next we will learn how to create RESTServices and use Actuator in Spring Boot. Later we will also learn how to deploy Spring Boot Application in IBM Liberty Profile and IBM WAS 8.5 Server.

This is the 2nd part of Getting Started with Spring Boot Series. Find all the parts here.

  1. An Introduction to Spring Boot
  2. How to Create Spring Boot Application Step by Step
  3. How to create RESTFul Webservices using Spring Boot
  4. How to deploy Spring Boot application in IBM Liberty and WAS 8.5

Step-by-step Spring Boot RESTful web services example in Java using STS


In a previous article about important RESTful principles and how to create a beautiful RESTful API, I used the example of a web service that kept track of an ongoing, global score for an online rock-paper-scissors application. In this step-by-step Spring Boot RESTful web services example, we’ll implement that scenario using the Spring Web APIs and the Eclipse based SpringSource Tool Suite (STS) as the IDE.

Review of the RESTful API

The RESTful score service will provide the following functions:

RESTful clients can find out the current number of wins, losses and ties through a GET request to the following URL:

www.mcnz.com/rps/score | GET

This invocation will return a JSON string in the following format:

{ "wins":"5", "losses":"3", "ties": "0"}

RESTful clients can update the score by invocating the same URL through a PUT invocation while also passing query parameters. Again, the program will return a JSON-based representation of the score after the update. A better design would be to use JSON as the payload, but query parameters are used here for the sake of simplicity.

www.mcnz.com/rps/score?wins=1&losses=2&ties=3 | PUT

With the RESTful API, the user cannot directly set the number of wins, losses or ties. The client can only use a POST invocation to increment values one at a time. This is not an idempotent function, so it is handled through a POST. In this case, a simple number is returned to the program as opposed to a JSON string.

You can use a simple GET invocation on the appropriate resource locator to obtain the number of wins, losses or ties:

www.mcnz.com/rps/score/wins | GET

www.mcnz.com/rps/score/ties | GET

www.mcnz.com/rps/score/losses | GET

This step-by-step Spring Boot RESTful web services example in Java has very few prerequisites, but it does assume that you have the SpringSource Tool Suite (STS) installed. If that’s the case, you are ready to jump on the fast track to developing RESTful web services with Spring.

Step 1. Create the RESTful Spring Boot project

The first step in this exercise is to create a new Spring Boot project named restful-spring-example that uses both the Web and DevTools features. This is accomplished by kicking off the Spring Starter Project wizard in Eclipse. Select the Spring Web and DevTools options and click Finish on the Spring Boot project wizard.

Spring Boot project wizard
How to start a Spring Boot RESTful web services project

Step 2: Create the Java classes

The next step is to open the restful-spring-example project and create two classes: Score.java and ScoreService.java.

Right click on the com.mcnz.restful.spring.boot package and choose to create a new class named Score. The Score class is used to keep track of the global number of wins, losses and ties that occur in the online rock-paper-scissors game. The Score class will maintain the number of wins, losses and ties as static variables of type int. State should never be held within a RESTful web service, so this class represents the externalization of state.

package com.mcnz.restful.spring.boot;

public class Score {
  public static int WINS, LOSSES, TIES;

After you code the Score class, create a second Java component named ScoreService. We’ll use the ScoreService class to provide access to — and the ability to manipulate — the Score. The first iteration of the class used in this Spring Boot web service example will have getter methods that return the number of wins, losses and ties, along with update methods that can increment the number of wins, losses and ties by one.

Create the RESTful Spring Boot ScoreService class
How to create the ScoreService class for the step-by-step RESTful web services example

Here is the first iteration of the ScoreService class before we decorate it with RESTful annotations and subsequently configure it as a Spring Boot web service.

package com.mcnz.restful.spring.boot;
/* Spring Boot web service example class */
public class ScoreService {
   public String updateScore(int wins, int losses, int  ties) {
      Score.WINS = wins;
      Score.TIES = ties;
      Score.LOSSES = losses;
      /* to be updated to return JSON */
      return this.toString();

   public int increaseWins()   { return ++Score.WINS;   }
   public int increaseTies()   { return ++Score.TIES;   }
   public int increaseLosses() { return ++Score.LOSSES; }

   public int getWins()   { return Score.WINS;   }
   public int getTies()   { return Score.TIES;   }
   public int getLosses() { return Score.LOSSES; }

/* End of Spring Boot web service example class. */

Step 3: Annotate the Spring Boot example class

With the first iteration of the ScoreService component coded, the next step is to transform it into a Spring Boot RESTful web service by decorating the class declaration with the @RestController annotation. The @RestController annotation informs the Spring Boot framework that the class contains methods that will be invoked through a web-based resource URL.

public class ScoreService { … }

Step 4: Annotate RESTful Spring methods

Step four is to add @RequestMapping annotations to methods. These annotations define the HTTP method used along with the structure of the resource URLs that will be used to invoke them. In the previous tutorial about how to create beautiful RESTful APIs, we established that we would invoke the update methods through a POST, and all getter methods sensibly through a GET invocation. The URLs are all resource based, so use of the URL path is /score/wins to get information about the number of wins and the path /score/ties to increase the number of ties.

Fully decorated with Spring Boot RESTful web service annotations, the next iteration of the ScoreService class looks as follows:

/* Spring Boot web service example class */
public class ScoreService {

  @RequestMapping(value="/score", method=RequestMethod.PUT, )
  public String updateScore(int wins, int losses, int ties) {
     Score.WINS = wins;
     Score.TIES = ties;
     Score.LOSSES = losses;
     return this.toString(); /* to be updated to return JSON */
   @RequestMapping(value="/score/wins", method=RequestMethod.POST)
   public int increaseWins()   { return ++Score.WINS;   }
   @RequestMapping(value="/score/ties", method=RequestMethod.POST)
   public int increaseTies()   { return ++Score.TIES;   }

   @RequestMapping(value="/score/losses", method=RequestMethod.POST)
   public int increaseLosses() { return ++Score.LOSSES; }

   @RequestMapping(value="/score/wins", method=RequestMethod.GET)
   public int getWins()   { return Score.WINS;   }

   @RequestMapping(value="/score/ties", method=RequestMethod.GET)
   public int getTies()   { return Score.TIES;   }

   @RequestMapping(value="/score/losses", method=RequestMethod.GET)
   public int getLosses() { return Score.LOSSES; }
/* End of Spring Boot web service example class */

Step 5: Generate RESTful JSON responses

This step-by-step Spring Boot RESTful web services example needs to generate a JSON-based response for the client. There are excellent frameworks like Jackson and GSON, which you should use in larger projects, but for this simple RESTful web services example, we will simply employ some Java String manipulation to generate the JSON.

The getScore() method needs to return a JSON string formatted in the following manner:

{ "wins":"5", "losses":"3", "ties": "0"}

Here is how the un-annotated getScore() method looks when coded to return a JSON string:

public String getScore() {
  String pattern = 
     "{ \"wins\":\"%s\", \"losses\":\"%s\", \"ties\": \"%s\"}";
  return String.format(pattern,Score.WINS, Score.LOSSES, Score.TIES);

Note that you’ll use this same pattern match and String format approach again to return a JSON-based representation of the score in the updateScore method.

Since the getScore() method now returns JSON, you need to add a new produces attribute to the @RequestMapping annotation. The fully annotated getScore() method that indicates that JSON will be returned to the calling program looks as follows:

public String getScore() {
  String pattern = 
       "{ \"wins\":\"%s\", \"losses\":\"%s\", \"ties\": \"%s\"}";
  return String.format(pattern,  Score.WINS, Score.LOSSES, Score.TIES);

In order to generate JSON, the updateScore method follows a similar pattern of updated annotations and String manipulation within the code:


public String updateScore(int wins, int losses, int ties) {
  Score.WINS = wins;
  Score.TIES = ties;
  Score.LOSSES = losses;
 String pattern = 
     "{ \"wins\":\"%s\", \"losses\":\"%s\", \"ties\": \"%s\"}";
  return String.format(pattern,Score.WINS, Score.LOSSES, Score.TIES);     

QueryParam to method signature mapping

To update the ScoreService, the client will use the /score path while it passes query parameters to represent the number of wins, losses and ties. For example, a request to update the number of wins to 99, ties to 88 and losses to 7 would look like this:


As long as the updateScore method has method parameters that match the names of the query parameters, the Spring Boot web services framework will assign the queryParam values to the correspondingly named method signature parameter.


public String updateScore(int wins, int losses, int ties) { … }

The updateScore method will take the values passed into the method and assign them to the corresponding properties of the ScoreService class. An updated JSON string will be sent to the client indicating the new, updated value of the score. You’ll use the same process used to generate JSON in the getScore()method here. The full method implementation is as follows:


public String updateScore(int wins, int losses, int ties) {
  Score.WINS = wins;
  Score.TIES = ties;
  Score.LOSSES = losses;
  String pattern = 
     "{ \"wins\":\"%s\", \"losses\":\"%s\", \"ties\": \"%s\"}";
  return String.format(pattern, Score.WINS, Score.LOSSES, Score.TIES);

With the updateScore method coded, the step-by-step Spring Boot RESTful web services example is code complete, and the only steps left are to test and deploy.

Step 6:  Run the Spring Boot RESTful web service

To run the application, simply right click on the restful-spring-example project and choose Run As → Spring Boot App and Maven will package the application and deploy it to the STS server. When the console window indicates the Tomcat-based server has finished starting, open a browser window and go to localhost:8080/score/wins. A value of zero will appear.

Step 7: Test the RESTful Spring Boot service

To test the increaseWins method, run the following two CURL command in a Bash shell:

$ curl -X POST "http://localhost:8080/score/wins"
$ curl -X GET "http://localhost:8080/score/"

The output of the second command is:

{ "wins":"1", "losses":"0", "ties": "0"}

Now trigger a PUT invocation, with query parameters being used to carry the payload:

$ curl -X PUT "http://localhost:8080/score?wins=31&losses=11&ties=22"

This results in an output of:

{ "wins":"31", "losses":"11", "ties": "22"}

And that’s it, a complete, step-by-step Spring Boot RESTful web services example that creates a fully functional Spring Boot application.

How to improve the RESTful Spring example

Now there is plenty of room for improvement and expansion when it comes to this step-by-step Spring Boot RESTful web services example.

Obviously, using the static variables in the Score class is a poor way to manage state, so at the very least we should offload the job of state management to a JavaBean with an ObjectOutputStream. And neither a JavaBeans or RESTful web service should be responsible for data persistence, so there will be opportunities to integrate Hibernate, JPA and Spring Boot web services. We could also invoke the Spring Boot RESTful web service example through a Spring MVC app or a Spring RestTemplate instead of CURL, and of course, it would be nice to package this app in an executable JAR file with an embedded Tomcat or embedded WebSphere Liberty server and deploy it as a microservice. But all of those things would complicate the example and distract from the core purpose, which is to demonstrate just how easy it is to develop a RESTful Spring web service using the Spring Boot framework.

These aforementioned issues will be addressed in subsequent tutorials. The source code for this step-by-step Spring Boot RESTful web services example can be found on GitHub.

Spring Boot and Embedded Servers – Tomcat, Jetty and Undertow



This guide will help you understand why embedded servers are gaining popularity. We will discuss the different options that Spring Boot supports – Tomcat, Jetty and Undertow.

You will learn

  • What is an embedded server?
  • Why are embedded servers getting popular?
  • What are the different embedded servers that Spring Boot supports?
  • How do you switch from one embedded server to another?

What is an Embedded Server?

Think about what you would need to be able to deploy your application (typically) on a virtual machine.

  • Step 1 : Install Java
  • Step 2 : Install the Web/Application Server (Tomcat/Websphere/Weblogic etc)
  • Step 3 : Deploy the application war

What if we want to simplify this?

How about making the server a part of the application?

You would just need a virtual machine with Java installed and you would be able to directly deploy the application on the virtual machine. Isn’t it cool?

This idea is the genesis for Embedded Servers.

When we create an application deployable, we would embed the server (for example, tomcat) inside the deployable.

For example, for a Spring Boot Application, you can generate an application jar which contains Embedded Tomcat. You can run a web application as a normal Java application!

Embedded server implies that our deployable unit contains the binaries for the server (example, tomcat.jar).

Creating an Embedded Server Project with Spring Initializr

Spring Initializr http://start.spring.io/ is great tool to bootstrap your Spring Boot projects.


As shown in the image above, following steps have to be done

  • Launch Spring Initializr and choose the following
    • Choose com.in28minutes.springboot.tutorial.basics.example as Group
    • Choose spring-boot-tutorial-basics as Artifact
    • Choose following dependencies
      • Web
      • DevTools
  • Click Generate Project.
  • Import the project into Eclipse. File -> Import -> Existing Maven Project.

Default Embedded Server with Spring Boot – Tomcat

We have included Spring Boot Starter Web in our dependencies when creating the spring boot project.

Let’s take a quick look at the dependencies for spring-boot-starter-web


You can see that by default Starter Web includes a dependency on starter tomcat.

Starter Tomcat has the following dependencies.


Starter Tomcat brings in all the dependencies need to run Tomcat as an embedded server.

Run the web application using an Embedded Server

When you run SpringBootTutorialBasicsApplication.java as a Java Application, you would see that the server would start up and start serving requests.

An extract from the log

o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)

You can see that tomcat has started by default on port 8080.

You can customize the port in application.properties


When you do a ‘mvn clean install’ on the project, a jar artifact named spring-boot-tutorial-basics-0.0.1-SNAPSHOT.jar is generated.

This jar can be used to run the application on any machine where Java 8 is installed.

The tomcat embedded server is also packaged inside this jar

Using Jetty as Embedded Server with Spring Boot

Remove the existing dependency on spring-boot-starter-web and add these in.


Using Undertow as Embedded Server with Spring Boot

Remove the existing dependency on spring-boot-starter-web and add these in.


Embedded Server Spring Boot Configuration

Spring Boot provides a number of options to configure the embedded server through application.properties

server.compression.enabled=false # If response compression is enabled.
server.context-path= # Context path of the application.
server.display-name=application # Display name of the application.
server.error.include-stacktrace=never # When to include a "stacktrace" attribute.
server.error.path=/error # Path of the error controller.
server.error.whitelabel.enabled=true # Enable the default error page displayed in browsers in case of a server error.
server.port=8080 # Server HTTP port.
server.server-header= # Value to use for the Server response header (no header is sent if empty)
server.servlet-path=/ # Path of the main dispatcher servlet.

Here are a few Jetty specific options

server.jetty.acceptors= # Number of acceptor threads to use.
server.jetty.max-http-post-size=0 # Maximum size in bytes of the HTTP post or put content.
server.jetty.selectors= # Number of selector threads to use.

You can also configure ssl on the embedded server

server.ssl.ciphers= # Supported SSL ciphers.
server.ssl.client-auth= # Whether client authentication is wanted ("want") or needed ("need"). Requires a trust store.
server.ssl.enabled= # Enable SSL support.
server.ssl.enabled-protocols= # Enabled SSL protocols.
server.ssl.key-alias= # Alias that identifies the key in the key store.
server.ssl.key-password= # Password used to access the key in the key store.
server.ssl.key-store= # Path to the key store that holds the SSL certificate (typically a jks file).
server.ssl.key-store-password= # Password used to access the key store.
server.ssl.key-store-provider= # Provider for the key store.
server.ssl.key-store-type= # Type of the key store.
server.ssl.protocol=TLS # SSL protocol to use.
server.ssl.trust-store= # Trust store that holds SSL certificates.
server.ssl.trust-store-password= # Password used to access the trust store.
server.ssl.trust-store-provider= # Provider for the trust store.
server.ssl.trust-store-type= # Type of the trust store.

A few tomcat specific properties are listed below

server.tomcat.accept-count= # Maximum queue length for incoming connection requests when all possible request processing threads are in use.
server.tomcat.accesslog.directory=logs # Directory in which log files are created. Can be relative to the tomcat base dir or absolute.
server.tomcat.accesslog.enabled=false # Enable access log.
server.tomcat.basedir= # Tomcat base directory. If not specified a temporary directory will be used.
server.tomcat.max-connections= # Maximum number of connections that the server will accept and process at any given time.
server.tomcat.max-threads=0 # Maximum amount of worker threads.
server.tomcat.uri-encoding=UTF-8 # Character encoding to use to decode the URI.

For complete list options refer spring documentation – https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

Tutorial: Use Spring Boot to Build and Deploy WAR Files


Spring Boot makes it easy to create stand-alone Java web applications. However in production environments, a web container often already exists. How do we deploy our apps in these situations and have them run side-by-side with other servlets? In this tutorial, we’ll walk through how to use WAR files to do just that.

Getting Started with With Spring Boot, Tomcat, and WAR Files

In a previous tutorial, we built a simple RESTful web app using Spring Boot. I’m going to use this as a base and show how to deploy it into a container. You can grab the code for this tutorial on GitHub.

To ensure an existing Spring Boot app is container-ready one needs do three things
– Renaming the embedded Tomcat libraries
– Repackage the output file as a WAR
– Wire the application up as a servlet

Tomcat Libraries

Building a Spring Boot application produces a runnable jar file by default. If your app includes server functionality, then Tomcat will be bundled with it. We need to ensure the Tomcat libraries don’t clash with an existing container (since the container will include the same libraries).

When we do a clean clone of our repo (grab the code on GitHub if you haven’t yet) and do an mvn clean package we end up with a target directory containing our runnable jar.

This jar contains Tomcat libraries. To confirm this, we can rename it to .zip and look at the lib directory.
LIB Tomcat

You’ll see various .jar files starting with tomcat-. Some of these will clash with a running instance of Tomcat. We need to tell Spring Boot to move them.

To WAR! AKA: Build Your WAR Files

First, we must tell Spring Boot we want a WAR file as output. This is as easy as adding one line to our pom.xml.

Now when we build the package with

we will see a .war file inside our target directory:
WAR file in target directory

As before we can rename the file to .zip to see what’s inside. Everything is basically the same, just slightly re-ordered. Now lib is inside of WEB-INF anddemo` (where our project code sits) is in WEB-INF/classes.
Web INF Files

Renaming Tomcat

Next, we tell Spring Boot to move our Tomcat libraries out of this folder. In our previous pom.xml we included three dependencies for our project – one for REST, one for data access, and another for the database.

Now we append the Spring Boot Tomcat Starter to this (which links to the Tomcat libraries you need when embedding) and set the scope of the dependency to provided.

This will still include the .jar files as before but will put them in a new folder called lib-provided.

We can see this if we follow the same procedure as before. Once we mvn clean package and rename our .war to .zip we’ll see inside WEB-INF the new folder has appeared. Inside are all the embedded Tomcat libraries (and you’ll see they are no longer in lib).
Embedded Tomcat Libraries

Now our application will happily reside in a servlet container without clashing with its libraries.

Setting Up a Servlet

The only other thing we need to do is wire our application up to start as a servlet. And to do this we need to modify our application definition.

In the REST app mentioned our Application.java used the SpringBootApplication annotation on the main class and defined a main method.

To set the app up as a servlet we extend the main class with SpringBootServletInitializer and override the configure method using SpringApplicationBuilder.

And that’s it! This application will now happily run inside a Tomcat container!

Installing Tomcat

Deploying WAR files to Tomcat is as easy as copying the file to Tomcat’s webapps directory. But first, you need to install Tomcat. On Ubuntu, you can use apt-get.

This will install and start the server automatically on port 8080.

On Windows it’s just as easy – download and extract the binary distribution .zip file and run startup.bat in the bin directory. This will open up a console window showing the output of Catalina.
Tomcat Console

In both cases, you can check to see if everything is running by browsing to localhost:8080. You should see the Tomcat default homepage.

(Who knew Tomcat was so easy to use?!)

Copy the WAR File

The last step is copying the WAR to webapps. Here the name is important – whatever filename we choose will be used to map HTTP requests to our application. (All done automatically! I think this is amazing.) In an attempt to be more URL-friendly, I’m going to use demo.war.

On Ubuntu, this can be done with:

In Windows, use Explorer for the copy and then wait for the console window to show deployment messages.
WAR Deployment Message

And that’s it! Just by copying one file across our app is automatically booted and running side-by-side with the default Tomcat servlet.

Test Your WAR File Deployment

As before we test this by making calls using curl. Normally we called get on localhost but now our application is mapped to /demo/.

This shows you available URLs. To see what people objects are available you can use:

Or, create new ones with:

Note: In my testing I found the deploy on Windows to be somewhat brittle. Sometimes I needed to close and rerun startup.bat.

Run as a Standalone Application

One last thing – because our Tomcat libraries are still there (just moved) we are able to run this application on it’s own. So mvn spring-boot:run still works !




Hosted PaaS (Platform As A Service) offerings like Heroku and OpenShift are great but not always suitable or even possible to use. If you need or want full control over your data and servers, or you just want to host your latest side project but don’t want Heroku dyno sleeping you might just want to self host.

Traditionally self-hosting was painful and cumbersome but today there are plenty options to self-host your apps that are nearly as painless as a hosted PaaS solution. In this tutorial I will show you how to deploy an app on Dokku:

Dokku is an extensible, open source Platform as a Service that runs on a single server of your choice.

Dokku provides an environment very similar to Heroku technically, allowing Dokku to take advantage of Heroku buildpacks to deploy your apps. Dokku uses these buildpacks to automatically build Docker containers that can run your apps and services. Refer to the Dokku documentation for more information on Dokku.

For this tutorial we’ll be using this Spring Boot example app I’ve set up. It’s a very basic app with a single HTTP endpoint that serves up a semi-random quote retrieved from a Postgres database. It’s a completely vanilla Spring Boot app, except for a single file to instruct Dokku how to start the app but more on that later. Let’s get started!


Get a server with root access. Dokku requires at least 1GB of RAM and officially only supports Ubuntu 14.04 x64.

For convenience you’ll want to assign a DNS hostname (dokku.example.org) to your servers IP and preferably even assign a wildcard record so you can deploy apps on <app name>.dokku.example.org.


SSH into your server and execute the following command to kick off the Dokku installation. Run this either as root or make sure your user account has sudo permissions.

wget -qO- https://raw.githubusercontent.com/dokku/dokku/v0.4.14/bootstrap.sh | bash

Sit back, get some coffee, this will take a couple of minutes. When the command completes open your browser and navigate to the ip address or hostname assigned to your server to complete the Dokku setup.

Dokku setup

Provide your SSH public key here so you’ll be able to push your app to Dokku later via Git. Enable use virtualhost naming for apps and enter the hostname you assigned to your server in step 1.

That’s it, you now have a fully functional Dokku instance up and running! Let’s see what it takes to actually deploy an app.


We’re about ready to deploy our first app. In general if you want to deploy an app on Dokku you don’t need to make a lot of modifications to your app. Especially if your app adheres to the Twelve Factor guidelines you should be fine. Most importantly your app should allow configuration via environment variables or command line parameters.

Fortunately Spring Boot embraces the Twelve Factor guidelines. Spring Boot supports configuration via environment variables out of the box and it’s trivial to implement your own.

Looking at the example app I prepared there are two important things to notice:

1. I’ve created two property aliases to allow configuration via $PORT and $DATABASE_URL. This is not strictly necessary but I prefer the more generic environment variables over the Spring specific ones.

// application.properties

2. I’ve added a Procfile to instruct Dokku how to start our app. Dokku will read this file during deployment and use the web process to boot our app. You can read more about Procfiles here.

# Procfile
web: env DATABASE_URL=$JDBC_DATABASE_URL target/dokku-boot-demo-0.0.1-SNAPSHOT.jar

During deployment Dokku invokes mvn install on our app so it will build a jar. Here we instruct Dokku that to launch our app it needs to execute the jar. We set the $DATABASE_URL to $JDBC_DATABASE_URLwhich is an environment variable provided by the Java buildpack that formats the database connection string for JDBC compatibility.


Alright so now our app is Dokku compatible. Before we can push our app to Dokku we need to configure our application in Dokku. For simplicity enter the following dokku commands in an SSH session on your server. Later you can setup the Dokku CLI client to run these commands directly from your local machine.

First we’ll create our app in Dokku:

$ dokku apps:create my-app

Next we’ll install the Dokku Postgres plugin:

$ dokku plugin:install https://github.com/dokku/dokku-postgres.git postgres

This will pull in a Postgres Docker image so give it some time to complete.

Next create a Postgres instance for our app:

$ dokku postgres:create my-app-postgres

Link it to our app:

$ dokku postgres:link my-app-postgres my-app

That’s all the configuration we need, let’s actually deploy our app now!

First clone the example app to your local machine:

$ git clone https://github.com/kabisa/dokku-boot-demo.git
$ cd dokku-boot-demo

Dokku uses a Git push to deploy model, meaning that you push your app sources into Dokku using Git. To deploy you simply add a git remote to your repository pointing to Dokku and git push every time you want to deploy your latest changes.

Execute the following command in your shell. Replace dokku.example.org with your actual Dokku hostname.

$ git remote add dokku dokku@dokku.example.org:my-app

And finally push our app to Dokku:

$ git push dokku master

Dokku will now detect our app is a Java app, build a Docker image suitable to run Java apps, compile the app and run it.

You should see similar output as below:

Dokku deploy gif

Open your browser at http://my-app.dokku.example.org/ and see a nice random quote!


Dokku takes a bit of one time setup but once you have your Dokku instance ready, deploying new applications will be a breeze. Do note that Dokku was designed for simple single server setups. If you need fancy stuff like clustering, access control etc you might want to look at one of the more comprehensive projects in this space like FlynnDeis or Cloud Foundry.

Even though Dokku is quite simple, we’ve only scratched the surface of what it can do. You now have a fully functional Dokku instance so go ahead and explore the Dokku docs to see what more is possible!

If there’s no suitable Heroku buildpack for your app you can always deploy a raw Docker container using Dokku by simply including a Dockerfile in the root of your project.

If you’re planning to deploy a more complex Spring Boot app to Dokku you might want to look into Spring Cloud Connectors. Spring Cloud Connectors can automatically detect that you’re running in a cloud platform, and configure your HTTP port and database automatically for you. Spring Cloud Connectors officially don’t support Dokku, but the Heroku support works just fine with Dokku.

Also be sure to check out the plugins that Dokku offers to make use of databases, message brokers etc. There’s even a Dokku Let’s Encrypt plugin for dead easy Let’s Encrypt SSL certificates.

Happy deploying!

Me 2016 square


Full Stack Developer • Github: pascalw • Twitter: @_pascalw

Show Buttons
Hide Buttons