Integrating localstack in your Sprint Boot application

A while ago we presented localstack: a framework that mocks many AWS services allowing you to develop cloud application even when you don’t have Internet connection and without spending any cent.

Starting from that, we discovered recently a pretty nice library that can be used to integrate a Spring Boot application with localstack. In that way, with several lines of code, you can run your app with localstack, then run it with real AWS services only by switching an environment variable set when application starts.One more prerequisite: Docker must be installed and running on your machine.

The code can be inspected here.

Basically, when you start your application with local profile, in the background will be started also a Docker container with localstack and you consumes services from there.

On the other side, when other profile is selected (dev, staging, prod), then your application creates AWS clients using credentials provided as arguments.

All useful commands are provided in the README file.

How that works

All the magic is possible by creating AWS clients only when profile used by started is not local. Nothing so special, we know 🙂 But for the effort required to have this running, we think it’s worth to spend 5 minutes to have this flexibility.

We invite you to check and other options this library has, like starting localstack only with services that are useful for you. For our example, when we use only S3, it should be something like:

java  -jar target/demo-java-service-1.0-SAMPLE.jar

And then in logs you can see:

[/usr/local/bin/docker, run, -d, --rm, -p, :4567-4583, -e, HOSTNAME_EXTERNAL=localhost, -e, SERVICES=s3, localstack/localstack]

The documentation of that library explains how to integrate it in tests, but in our opinion this shouldn’t be done: for unit tests, we think it’s better to use a mocking library because it gives you more power to actually test that mocks behave as you expect. And for integration tests, run it with real AWS services to make sure you application runs as expected.

As always, we invite you to share with us your thoughts about this library.