February 12, 2016

Java Microservices With Spring

Java Frameworks

This is the second blog post in the series “Exploring the virtues of microservices,” with each one checking out different frameworks that established themselves in the Java industry as goto choices for establishing a microservices environment. The main goal of the series is to investigate what makes certain libraries so good at enabling microservices architecture. Last time we looked at how Play framework and the Akka library help you build forests of microservices and looked how they encourage you to ensure isolation, autonomy, and managing the state of the components at the code level. 

This time we focus on the Spring framework.

Spring by Pivotal logo

Spring and Java Application Development

For a long time, the Spring framework was the de-facto framework choice for web applications. It was created in response to heavy Java application servers of the past, and introduced a much more lightweight approach to creating web applications. The main principle of Spring that made it so popular was the dependency injection, which was added very early on. Of course, now we take dependency injection for granted and don’t even think about how revolutionary the idea was: you declare your component and the relationship between them and the framework takes care of the lifecycle of your components and wires them together into a useful graph of objects.

Nowadays, Spring has established its own ecosystem. There are tons of smaller web frameworks that have been created. Some actually quite good, some just optimized for the hello world scenario. But Spring hasn’t budged. So let’s see which qualities of the Spring framework make it an excellent choice for the microservices architecture.

Java Microservices and Spring

The main virtue of the Spring framework, I truly believe, is not in the particular framework-y magic itself. There are many other web frameworks, or database access libraries, and http client libraries and some of them might be better than whatever is the default choice in Spring. In my opinion, it’s all about the integrations. If you consider how many libraries Spring integrates with, the competition fades away. A good way to convince yourself is to look at the number of guides or how-tos are available on the Spring website: http://spring.io/guides. All of them follow one important pattern: specify the correct dependency, initialize a Spring component and autowire library beans into it. Then use it as you would normally use your own object. Done!

However, being a very advanced project that integrates with everything in the world alone is not enough for microservices. In fact, the following virtues of the Spring framework are what we’re going to focus on in this post:

  • Dependency injection and integrations
  • Super easy central configuration service creation
  • A straightforward service discovery registry

Spring Dependency Injection & Integrations

Dependency injection and integrations with other libraries is the heartbeat of Spring framework. In a nutshell, you annotate your object with the @Component annotation, and upon its discovery Spring will initialize the object, inject all the necessary sub-components into its fields and add the object into the context of your application. Building multiple components will just enhance this context with more and more objects that are easily accessible to each other.

Now this mechanism becomes very useful when you want to create an integration with libraries. Imagine you have a library that accesses Twitter to post tweets and provides a nice API in the form of a Twitter class. The integration project will need to declare the library as a dependency, provide its own Twitter class that is marked with the @Component annotation and will consume the configuration such as credentials to a Twitter account. Spring will then pass all calls for this service to the correctly configured library Twitter instance on your behalf.

In the main project you’ll just need to declare a dependency and @Autowire this Spring Twitter bean into your code. The result is astonishingly easy to use. Here’s a writeup of what Simon Maple could build in 2 hours with Spring Boot and its social networks integrations, it’s pretty convincing!

Central Microservices Configuration

The next step to building a proper microservices deployment is to ensure that all the microservices get configured properly. This means that they should ideally grab their configuration from another web-service, that acts like a central configuration hub.

Long story short, Spring has a Spring cloud initiative, that makes this task an absolute no-brainer. All you have to do to set up the configuration service is to create a new Spring Boot application and add the @EnableConfigServer annotation to the application, as follows:

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

See, I told you it was that easy! The @EnableConfigServer is a Spring Cloud annotation that takes care of everything you need to build a configuration server. The only thing left is to specify the location of where your config is going to be taken from, such as a file or a git repository, or a database. Straight away we have the central most piece of our infrastructure ready. Now other services in the deployment will initialize themselves, come to this Configuration Server and obtain the rest of the configuration. This is essential, as now you’ll be able to configure them by type, scale automatically and so on.

Service Discovery

The next thing you’ll need to know about Spring which makes it so suitable for use with microservices is the ease with which you can set up a registry for your services. As the registry is a microservice itself, it allows other services to register themselves as a service of a particular type. The client service can then query the URLs for all the dependencies it needs and interact with them.

This saves you a lot of effort on network topology orchestration, simplifies the configuration and makes scaling your deployment much easier. You just need to spin up the services and they will both register and make themselves available. They will query the services they need to consume and can grab that information from the registry as well.

By now you’re probably seeing the value of the discovery registry for your microservices deployments and have started wondering if it’s hard to implement. The answer is: Spring has you covered.

Spring integrates with Eureka REST service registry by Netflix. And as usual, with some Spring Boot magic, you just need a couple of annotations on your Application class to make it work.

public class EurekaApplication {
	public static void main(String[] args) throws Exception {
		SpringApplication.run(EurekaApplication.class, args);

The code above will do everything necessary to make the service registry fully operational. That’s no moon. Even better, you can check out the full project on the Github, or run it as a docker container that is published in the dockerhub at springcloud/eureka.

Simple Project Setup With Spring Boot

The central configuration and the service discovery registry make creating one more microservice a breeze. So with Spring you get the full support of your microservices architecture out of the box. With these two problems effectively solved, you can concentrate on making your service amazing. And since literally every library out there that you might think of has some level of Spring integration ready, out the box. Slap on a couple of annotations, and you’ll get a fully configured bean to do database work, parse graphs, process text, do some security or cryptography (if you’re into that kind of stuff) and well everything besides!

If you’re not convinced, here’s an example of a minimal Spring Boot application. That’s all the code you need to serve the Hello world Spring boot application. Albeit, it’s in Groovy, but Java’s version will be just a tad longer.

class HelloRestController {
  def hi(@PathVariable String name) {
    [greetings : “Hello, “ + name + “!”]

Note the mighty @Grab annotation that will find the artifact by id, which in this case is the spring-boot-starter-actuator. This is automatically downloaded and added to the classpath.

Anyway, as this is a working example you should try to run it! You’ll just need to call the following spring command:

spring run hi.groovy

You’ll be welcomed by a warm “Hello, username” after an HTTP request to localhost:8080. Also, I cannot say how happy I am with the project initializer available at: start.spring.io. You literally click what libraries you want to use and get the fully initialized project in seconds!

Spring initializr project starter

This is how easy it is to get a microservice up and running with Spring. Now you just need to create a ton of them so your operations team will love you more and more. Each one being tasked with exactly one job that it needs to do and voila, they can all be configured through a central service. Additionally, they will all be aware of each other through the Eureka service registry and they will all work together really really well.

Spring for Java Microservices

The Spring framework is great for a microservices architecture because it enables almost trivial creation of fully functional applications that don’t deviate from a model of programming that we all know and love.

The best part is that because Spring ties these small applications together into a service, communicating over a network is a no-brainer. With central configuration services and the service auto-discovery registry pieces which are available to you out of the box, it’s easy to build a cluster of microservices.

You can then bathe in the sea of external library integrations which exist for Spring, making it incredibly productive out of the box.

Additional Resources