Book Image

Mastering Spring 5.0

By : In28Minutes Official
Book Image

Mastering Spring 5.0

By: In28Minutes Official

Overview of this book

Spring 5.0 is due to arrive with a myriad of new and exciting features that will change the way we’ve used the framework so far. This book will show you this evolution—from solving the problems of testable applications to building distributed applications on the cloud. The book begins with an insight into the new features in Spring 5.0 and shows you how to build an application using Spring MVC. You will realize how application architectures have evolved from monoliths to those built around microservices. You will then get a thorough understanding of how to build and extend microservices using Spring Boot. You will also understand how to build and deploy Cloud-Native microservices with Spring Cloud. The advanced features of Spring Boot will be illustrated through powerful examples. We will be introduced to a JVM language that’s quickly gaining popularity - Kotlin. Also, we will discuss how to set up a Kotlin project in Eclipse. By the end of the book, you will be equipped with the knowledge and best practices required to develop microservices with the Spring Framework.
Table of Contents (20 chapters)
Title Page
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

New features in Spring Framework 5.0


Spring Framework 5.0 is the first major upgrade in Spring Framework, almost four years after Spring Framework 4.0. In this time frame, one of the major developments has been the evolution of the Spring Boot project. We will discuss the new features in Spring Boot 2.0 in the next section.

One of the biggest features of Spring Framework 5.0 is Reactive Programming. Core reactive programming features and support for reactive endpoints are available out of the box with Spring Framework 5.0. The list of important changes includes the following:

  • Baseline upgrades
  • JDK 9 runtime compatibility
  • Usage of JDK 8 features in the Spring Framework code
  • Reactive programming support
  • A functional web framework
  • Java modularity with Jigsaw
  • Kotlin support
  • Dropped features

Baseline upgrades

Spring Framework 5.0 has JDK 8 and Java EE 7 baseline. Basically, it means that previous JDK and Java EE versions are not supported anymore.

Some of the important baseline Java EE 7 specifications for Spring Framework 5.0 are listed as follows:

  • Servlet 3.1
  • JMS 2.0
  • JPA 2.1
  • JAX-RS 2.0
  • Bean Validation 1.1

There are many changes to the minimum supported versions of several Java frameworks. The following list contains some of the minimum supported versions of prominent frameworks:

  • Hibernate 5
  • Jackson 2.6
  • EhCache 2.10
  • JUnit 5
  • Tiles 3

The following list shows the supported server versions:

  • Tomcat 8.5+
  • Jetty 9.4+
  • WildFly 10+
  • Netty 4.1+ (for web reactive programming with Spring Web Flux)
  • Undertow 1.4+ (for web reactive programming with Spring Web Flux)

Applications using earlier versions of any of the preceding specifications/frameworks need to be upgraded at least to the previously listed versions before they can use Spring Framework 5.0.

JDK 9 runtime compatibility

JDK 9 is expected to be released mid-2017. Spring Framework 5.0 is expected to have runtime compatibility with JDK 9.

Usage of JDK 8 features in Spring Framework code

The Spring Framework 4.x baseline version is Java SE 6. This means that it supports Java 6, 7, and 8. Having to support Java SE 6 and 7 puts constraints on the Spring Framework code. The framework code cannot use any of the new features in Java 8. So, while the rest of the world upgraded to Java 8, the code in Spring Framework (at least the major parts) was restricted to using earlier versions of Java.

With Spring Framework 5.0, the baseline version is Java 8. Spring Framework code is now upgraded to use the new features in Java 8. This will result in more readable and performant framework code. Some of the Java 8 features used are as follows:

  • Java 8 default methods in core Spring interfaces
  • Internal code improvements based on Java 8 reflection enhancements
  • Use of functional programming in the framework code--lambdas and streams

Reactive programming support

Reactive programming is one of the most important features of Spring Framework 5.0.

Microservices architectures are typically built around event-based communication. Applications are built to react to events (or messages).

Reactive programming provides an alternate style of programming focused on building applications that react to events.

While Java 8 does not have built-in suppport for reactive programming, there are a number of frameworks that provide support for reactive programming:

  • Reactive Streams: Language-neutral attempt to define reactive APIs.
  • Reactor: Java implementation of Reactive Streams provided by the Spring Pivotal team.
  • Spring WebFlux: Enables the development of web applications based on reactive programming. Provides a programming model similar to Spring MVC.

We will discuss Reactive Programming and how you can implement it with Spring Web Flux in Chapter 11, Reactive Programming.

Functional web framework

Building on top of the reactive features, Spring 5 also provides a functional web framework.

A functional web framework provides features to define endpoints using functional programming style. A simple hello world example is shown here:

    RouterFunction<String> route =
    route(GET("/hello-world"),
    request -> Response.ok().body(fromObject("Hello World")));

A functional web framework can also be used to define more complex routes, as shown in the following example:

    RouterFunction<?> route = route(GET("/todos/{id}"),
    request -> {
       Mono<Todo> todo = Mono.justOrEmpty(request.pathVariable("id"))
       .map(Integer::valueOf)
       .then(repository::getTodo);
       return Response.ok().body(fromPublisher(todo, Todo.class));
      })
     .and(route(GET("/todos"),
     request -> {
       Flux<Todo> people = repository.allTodos();
       return Response.ok().body(fromPublisher(people, Todo.class));
     }))
    .and(route(POST("/todos"),
    request -> {
      Mono<Todo> todo = request.body(toMono(Todo.class));
      return Response.ok().build(repository.saveTodo(todo));
    }));

A couple of important things to note are as follows:

  • RouterFunction evaluates the matching condition to route requests to the appropriate handler function
  • We are defining three endpoints, two GETs, and one POST, and mapping them to different handler functions

We will discuss Mono and Flux in more detail in Chapter 11, Reactive Programming.

Java modularity with Jigsaw

Until Java 8, the Java platform was not modular. A couple of important problems resulted out of this:

  • Platform Bloat: Java modularity has not been a cause of concern in the last couple of decades. However, with Internet of Things (IOT) and new lightweight platforms such as Node.js, there is an urgent need to address the bloat of the Java platform. (Initial versions of JDK were less than 10 MB in size. Recent versions of JDK need more than 200 MB.)
  • JAR Hell: Another important concern is the problem of JAR Hell. When Java ClassLoader finds a class, it will not see whether there are other definitions for the class available. It immediately loads the first class that is found. If two different parts of the application need the same class from different jars, there is no way for them to specify the jar from which the class has to be loaded.

Open System Gateway initiative (OSGi) is one of the initiatives, started way back in 1999, to bring modularity into Java applications.

Each module (referred to as bundle) defines the following:

  • imports: Other bundles that the module uses
  • exports: Packages that this bundle exports

Each module can have its own life cycle. It can be installed, started, and stopped on its own.

Jigsaw is an initiative under Java Community Process (JCP), started with Java 7, to bring modularity into Java. It has two main aims:

  • Defining and implementing a modular structure for JDK
  • Defining a module system for applications built on the Java platform

Jigsaw is expected to be part of Java 9 and Spring Framework 5.0 is expected to include basic support for Jigsaw modules.

Kotlin support

Kotlin is a statically typed JVM language that enables code that is expressive, short, and readable. Spring framework 5.0 has good support for Kotlin.

Consider a simple Kotlin program illustrating a data class, as shown here:

    import java.util.*
    data class Todo(var description: String, var name: String, var  
    targetDate : Date)
    fun main(args: Array<String>) {
      var todo = Todo("Learn Spring Boot", "Jack", Date())
      println(todo)
        //Todo(description=Learn Spring Boot, name=Jack, 
        //targetDate=Mon May 22 04:26:22 UTC 2017)
      var todo2 = todo.copy(name = "Jill")
      println(todo2)
         //Todo(description=Learn Spring Boot, name=Jill, 
         //targetDate=Mon May 22 04:26:22 UTC 2017)
      var todo3 = todo.copy()
      println(todo3.equals(todo)) //true
    }  

In fewer than 10 lines of code, we created and tested a data bean with three properties and the following functions:

  • equals()
  • hashCode()
  • toString()
  • copy()

Kotlin is strongly typed. But there is no need to specify the type of each variable explicitly:

    val arrayList = arrayListOf("Item1", "Item2", "Item3") 
    // Type is ArrayList

Named arguments allow you to specify the names of arguments when calling methods, resulting in more readable code:

    var todo = Todo(description = "Learn Spring Boot", 
    name = "Jack", targetDate = Date())

Kotlin makes functional programming simpler by providing default variables (it) and methods such as take, drop, and so on:

    var first3TodosOfJack = students.filter { it.name == "Jack"   
     }.take(3)

You can also specify default values for arguments in Kotlin:

    import java.util.*
    data class Todo(var description: String, var name: String, var
    targetDate : Date = Date())
    fun main(args: Array<String>) {
      var todo = Todo(description = "Learn Spring Boot", name = "Jack")
    }

With all its features making the code concise and expressive, we expect Kotlin to be a language to be learned for the .

We will discuss more about Kotlin in Chapter 13, Working with Kotlin in Spring.

Dropped features

Spring Framework 5 is a major Spring release with substantial increase in the baselines. Along with the increase in baseline versions for Java, Java EE and a few other frameworks, Spring Framework 5 removed support for a few frameworks:

  • Portlet
  • Velocity
  • JasperReports
  • XMLBeans
  • JDO
  • Guava

If you are using any of the preceding frameworks, it is recommended that you plan a migration and stay with Spring Framework 4.3--which has support until 2019.