Home Programming Mastering Spring 5.0

Mastering Spring 5.0

By In28Minutes Official
books-svg-icon Book
eBook $43.99 $29.99
Print $54.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $43.99 $29.99
Print $54.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Evolution to Spring Framework 5.0
About 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.
Publication date:
June 2017
Publisher
Packt
Pages
496
ISBN
9781787123175

 

Chapter 1. Evolution to Spring Framework 5.0

The first version of Spring Framework 1.0 was released in March 2004. For more than a decade and a half, Spring Framework remained the framework of choice to build Java applications.

In the relatively young and dynamic world of Java frameworks, a decade is a long time.

In this chapter, we start with understanding the core features of Spring Framework. We will look at why the Spring Framework became popular and how it adapted to remain the framework of choice. After taking a quick look at the important modules in the Spring Framework, we will jump into the world of Spring Projects. We will end the chapter by looking at the new features in Spring Framework 5.0.

This chapter will answer the following questions:

  • Why is Spring Framework popular?
  • How has Spring Framework adapted to the evolution of application architectures?
  • What are the important modules in Spring Framework?
  • Where does Spring Framework fit in the umbrella of Spring Projects?
  • What are the new features in Spring Framework 5.0?
 

Spring Framework


The Spring website (https://projects.spring.io/spring-framework/) defines Spring Framework as follows: The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications.

Spring Framework is used to wire enterprise Java applications. The main aim of Spring Framework is to take care of all the technical plumbing that is needed in order to connect the different parts of an application. This allows programmers to focus on the crux of their jobs--writing business logic.

Problems with EJB

Spring Framework was released in March 2004. When the first version of Spring Framework was released, the popular way of developing an enterprise application was using Enterprise Java Beans (EJB) 2.1.

Developing and deploying EJBs was a cumbersome process. While EJBs made the distribution of components easier, developing, unit testing, and deploying them was not easy. The initial versions of EJBs (1.0, 2.0, 2.1) had a complex Application Programmer Interface (API), leading to a perception (and truth in most applications) that the complexity introduced far outweighed the benefits:

  • Difficult to unit test. Actually, difficult to test outside the EJB Container.
  • Multiple interfaces need to be implemented with a number of unnecessary methods.
  • Cumbersome and tedious exception handling.
  • Inconvenient deployment descriptors.

Spring Framework was introduced as a lightweight framework aimed at making developing Java EE applications simpler.

 

Why is Spring Framework popular?


The first version of Spring Framework was released in March 2004. In the subsequent decade and a half, the use and popularity of Spring Framework only grew.

The important reasons behind the popularity of Spring Framework are as follows:

  • Simplified unit testing--because of dependency injection
  • Reduction in plumbing code
  • Architectural flexibility
  • Keeping up with changing times

Let's discuss each of these in detail.

Simplified unit testing

Earlier versions of EJBs were very difficult to unit test. In fact, it was difficult to run EJBs outside the container (as of version 2.1). The only way to test them was to deploy them in a container.

Spring Framework brought in the concept of Dependency Injection (DI). We will discuss dependency injection in complete detail in Chapter 2, Dependency Injection.

The dependency injection enables unit testing by making it easy to replace the dependencies with their mocks. We do not need to deploy the entire application to unit test it.

Simplifying unit testing has multiple benefits:

  • Programmers are more productive
  • Defects are found earlier so they are less costly to fix
  • Applications have automated unit tests, which can run in Continuous Integration builds, preventing future defects

Reduction in plumbing code

Before Spring Framework, typical J2EE (or Java EE, as it is called now) applications contained a lot of plumbing code. For example: getting a database connection, exception handling code, transaction management code, logging code, and a lot more.

Let's take a look at a simple example of executing a query using prepared statement:

    PreparedStatement st = null;
    try {
          st = conn.prepareStatement(INSERT_TODO_QUERY);
          st.setString(1, bean.getDescription());
          st.setBoolean(2, bean.isDone());
          st.execute();
        } 
    catch (SQLException e) {
          logger.error("Failed : " + INSERT_TODO_QUERY, e);
     } finally {
                if (st != null) {
           try {
           st.close();
          } catch (SQLException e) {
           // Ignore - nothing to do..
          }
       }
     }

In the preceding example, there are four lines of business logic and more than 10 lines of plumbing code.

With Spring Framework, the same logic can be applied in a couple of lines:

    jdbcTemplate.update(INSERT_TODO_QUERY, 
    bean.getDescription(), bean.isDone());

How does Spring Framework do this magic?

In the preceding example, Spring JDBC (and Spring, in general) converts most checked exceptions into unchecked exceptions. Typically, when a query fails, there is not a lot we can do--other than to close the statement and fail the transaction. Instead of implementing exception handling in every method, we can have centralized exception handling and inject it in using Spring Aspect-Oriented Programming (AOP).

Spring JDBC removes the need to create all the plumbing code involved in getting a connection, creating a prepared statement, and so on. The jdbcTemplate class can be created in the Spring context and injected into the Data Access Object (DAO) class wherever it is needed.

Similar to the preceding example, Spring JMS, Spring AOP, and other Spring modules help in reducing a lot of plumbing code.

Spring Framework lets the programmer focus on the primary job of a programmer-- writing business logic.

Avoiding all the plumbing code also has another great benefit--reduced duplication in code. Since all code for transaction management, exception handling, and so on (typically, all your cross-cutting concerns) is implemented at one place, it is easier to maintain.

Architectural flexibility

Spring Framework is modular. It is built as a set of independent modules built on top of the core Spring modules. Most of the Spring modules are independent--you can use one of them without having to use others.

Let's look at a few examples:

  • In the web layer, Spring offers a framework of its own--Spring MVC. However, Spring has great support for Struts, Vaadin, JSF, or any web framework of your choice.
  • Spring Beans can provide lightweight implementation for your business logic. However, Spring can be integrated with EJBs as well.
  • In the data layer, Spring simplifies JDBC with its Spring JDBC module. However, Spring has great support for any of your preferred data layer frameworks--JPA, Hibernate (with or without JPA), or iBatis.
  • You have the option of implementing your cross-cutting concerns (logging, transaction management, security, and so on) with Spring AOP. Or, you can integrate with a fully fledged AOP implementation such as AspectJ.

Spring Framework does not want to be the jack-of-all-trades. While focusing on its core job of reducing coupling between different parts of the application and making them testable, Spring provides great integration with frameworks of your choice. This means you have flexibility in your architecture--if you do not want to use a specific framework, you can easily replace it with another.

Keep up with changing times

The first version of Spring Framework focused on making applications testable. However, as time moved on, there were new challenges. Spring Framework managed to evolve and stay ahead of the curve with the flexibility and modules that are offered. A couple of examples are listed as follows:

  • Annotations were introduced in Java 5. Spring Framework (version 2.5 – Nov 2007) was ahead of Java EE in introducing an annotation-based controller model for Spring MVC. Developers using Java EE had to wait until Java EE 6 (Dec 2009 – 2 years) before having comparable functionality.
  • Spring Framework introduced a number of abstractions ahead of Java EE to keep the application decoupled from specific implementation. Caching API provides a case in point. Spring provided a transparent caching support in Spring 3.1. Java EE came up with JSR-107 for JCache (in 2014)--support for which was provided in Spring 4.1.

Another important thing Spring brings in is the umbrella of Spring Projects. Spring Framework is just one of the many projects under Spring Projects. We will discuss the different Spring Projects in a separate section. The following examples illustrate how Spring managed to stay ahead of times with new Spring Projects:

  • Spring Batch defines a new approach to building Java Batch applications. We had to wait until Java EE 7 (June 2013) to have comparable batch application specification in Java EE.
  • As architecture evolved toward Cloud and microservices, Spring came up with new Cloud-oriented Spring Projects. Spring Cloud helps in simplifying the development and deployment of microservices. Spring Cloud Data Flow provides orchestrations around microservice applications.
 

Spring modules


The modularity of Spring Framework is one of the most important reasons for its widespread used. Spring Framework is highly modular with more than 20 different modules--having clearly defined boundaries.

The following figure shows different Spring modules--organized by the layer of application they are typically used in:

We will start with discussing the Spring Core Container before moving on to other modules grouped by the application layer they are typically used in.

Spring Core Container

Spring Core Container provides the core features of Spring Framework--dependency injection, IoC (Inversion of Control) container, and the application context. We will learn more about DI and IoC Container in Chapter 2, Dependency Injection.

Important core Spring modules are listed in the following table:

Module/Artifact

Use

spring-core

Utilities used by other Spring modules.

spring-beans

Support for Spring beans. In combination with spring-core provides the core feature of Spring Framework--dependency injection. Includes implementation of BeanFactory.

spring-context

Implements ApplicationContext, which extends BeanFactory and provides support to load resources and internationalization, among others.

spring-expression

Extends EL (Expression Language from JSP) and provides a language for bean property (including arrays and collections) access and manipulations.

Cross-cutting concerns

Cross-cutting concerns are applicable to all application layers--logging and security, among others. AOP is typically used to implement cross-cutting concerns.

Unit tests and integration tests fit this category since they are applicable to all layers.

Important Spring modules related to cross-cutting concerns are listed as follows:

Module/Artifact

Use

spring-aop

Provides basic support for Aspect-Oriented Programming--with method interceptors and pointcuts.

spring-aspects

Provides integration with the most popular and fully featured AOP framework, AspectJ.

spring-instrument

Provides basic instrumentation support.

spring-test

Provides basic support for unit testing and integration testing.

Web

Spring provides its own MVC framework, Spring MVC, other than providing great integration with popular web frameworks such as Struts.

Important artifacts/modules are listed as follows:

  • spring-web: Provides basic web features, such as multi-part file upload. Provides support for integration with other web frameworks, such as Struts.
  • spring-webmvc: Provides a fully featured web MVC framework--Spring MVC, which includes features to implement REST services as well.

We will cover Spring MVC and develop web applicaitions and rest services with it in Chapter 3, Building Web Application with Spring MVC and Chapter 5, Building Microservices with Spring Boot.

Business

The business layer is focused on executing the business logic of the applications. With Spring, business logic is typically implemented in Plain Old Java Object (POJO).

Spring Transactions (spring-tx) provides declarative transaction management for POJO and other classes.

Data

The data layer in applications typically talks to the database and/or the external interfaces. Some of the important Spring modules related to the data layer are listed in the following table:

Module/Artifact

Use

spring-jdbc

Provides abstraction around JDBC to avoid boilerplate code.

spring-orm

Provides integration with ORM frameworks and specifications-- JPA and Hibernate, among others.

spring-oxm

Provides an object to XML mapping integration. Supports frameworks such as JAXB, Castor, and so on.

spring-jms

Provides abstraction around JMS to avoid boilerplate code.

 

Spring Projects


While Spring Framework provides the base for core features of enterprise applications (DI, web, data), other Spring Projects explore integration and solutions to other problems in the enterprise space--deployment, Cloud, Big Data, Batch and Security, among others.

Some of the important Spring Projects are listed as follows:

  • Spring Boot
  • Spring Cloud
  • Spring Data
  • Spring Batch
  • Spring Security
  • Spring HATEOAS

Spring Boot

Some of the challenges while developing microservices and web applications are as follows:

  • Making framework choices and deciding compatible framework versions
  • Providing mechanisms for externalizing configuration--properties that can change from one environment to another
  • Health checks and monitoring--providing alerts if a specific part of the application is down
  • Deciding the deployment environment and configuring the application for it

Spring Boot solves all these problems out of the box by taking an opinionated view of how applications have to be developed.

We will look at Spring Boot in depth in two chapters--Chapter 5, Building Microservices with Spring Boot and Chapter 7, Advanced Spring Boot Features.

Spring Cloud

It is not an exaggeration to say The world is moving to the Cloud.

Cloud Native microservices and applications are the order of the day. We will discuss this in detail in Chapter 4, Evolution toward Microservices and Cloud-Native Applications.

Spring is taking rapid strides toward making application development for the Cloud simpler with Spring Cloud.

Spring Cloud provides solutions for common patterns in distributed systems. Spring Cloud enables developers to quickly create applications that implement common patterns. Some of the common patterns implemented in Spring Cloud are listed as follows:

  • Configuration management
  • Service discovery
  • Circuit breakers
  • Intelligent routing

We will discuss Spring Cloud and its varied range features in more detail in Chapter 9, Spring Cloud.

Spring Data

There are multiple sources of data in today's world--SQL (relational) and a variety of NOSQL databases. Spring Data tries to provide a consistent data-access approach to all these different kinds of databases.

Spring Data provides integration with a varied range of specifications and/or data stores:

  • JPA
  • MongoDB
  • Redis
  • Solr
  • Gemfire
  • Apache Cassandra

Some of the important features are listed as follows:

  • Provides abstractions around repository and object mappings--by determining queries from method names
  • Simple Spring integration
  • Integration with Spring MVC controllers
  • Advanced automatic auditing features--created by, created date, last changed by, and last changed date

We will discuss Spring Data in more detail in Chapter 8, Spring Data.

Spring Batch

Enterprise applications today process large volumes of data using batch programs. The needs of these applications are very similar. Spring Batch provides solutions for high- volume batch programs with high performance requirements.

Important features in Spring Batch are as follows:

  • The ability to start, stop, and restart jobs--including the ability to restart failed jobs from the point where they failed
  • The ability to process data in chunks
  • The ability to retry steps or to skip steps on failure
  • Web-based administration interface

Spring Security

Authentication is the process of identifying the user. Authorization is the process of ensuring that a user has access to perform the identified action on the resource.

Authentication and authorization are critical parts of Enterprise applications, both web applications and web services. Spring Security provides declarative authentication and authorization for Java based applications.

Important features in Spring Security are as follows:

  • Simplified authentication and authorization
  • Great integration with Spring MVC and Servlet APIs
  • Support to prevent common security attacks--cross-site forgery request (CSRF) and Session Fixation
  • Modules available for integration with SAML and LDAP

We will discuss how to secure web applications with Spring Security in Chapter 3, Building Web Application with Spring MVC.

We will discuss how to secure REST Services with Basic and OAuth authentication mechanisms using Spring Security in Chapter 6, Extending Microservices.

Spring HATEOAS

HATEOAS stands for Hypermedia as The Engine of Application State. Though it sounds complex, it is quite a simple concept. Its main aim is to decouple the server (the provider of the service) from the client (the consumer of the service).

The service provider provides the service consumer with information about what other actions can be performed on the resource.

Spring HATEOAS provides a HATEOAS implementation--especially for the REST services implemented with Spring MVC.

Important features in Spring HATEOAS are as follows:

  • Simplified definition of links pointing to service methods, making the links less fragile
  • Support for JAXB (XML-based) and JSON integration
  • Support for service consumer (client side)

We will discuss how to use HATEOAS in Chapter 6, Extending Microservices.

 

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.

 

Spring Boot 2.0 new features


The first version of Spring Boot was released in 2014. The following are some of the important updates expected in Spring Boot 2.0:

  • The baseline JDK version is Java 8
  • The baseline Spring Version is Spring Framework 5.0
  • Spring Boot 2.0 has support for Reactive Web programming with WebFlux

Minimum supported versions of some important frameworks are listed as follows:

  • Jetty 9.4
  • Tomcat 8.5
  • Hibernate 5.2
  • Gradle 3.4

We will discuss Spring Boot extensively in Chapter 5, Building Microservices with Spring Boot and Chapter 7, Advanced Spring Boot Features.

 

Summary


Over the course of the last decade and a half, Spring Framework has dramatically improved the experience of developing Java Enterprise applications. With Spring Framework 5.0, it brings in a lot of features while significantly increasing the baselines.

In the subsequent chapters, we will cover dependency injection and understand how we can develop web applications with Spring MVC. After that, we will move into the world of microservices. In Chapters 5, Building Microservices with Spring Boot, Chapter 6, Extending Microservices, and Chapter 7, Advanced Spring Boot Features, we will cover how Spring Boot makes the creation of microservices simpler. We will then shift our attention to building applications in the Cloud with Spring Cloud and Spring Cloud Data Flow.

About the Author
  • In28Minutes Official

    Ranga Rao Karanam is the founder of in28Minutes, a company that trains 300,000 developers across the globe in relation to the cloud, microservices, Spring, Spring Boot, and Containers. He loves programming, and loves consulting for start-ups on developing scalable cloud applications and following modern development practices, such as BDD, continuous delivery, and DevOps. In his spare time, he loves hiking, cricket, and tennis. His ambition is to spend a year hiking the Himalayas.

    Browse publications by this author
Latest Reviews (5 reviews total)
Great book useful for learners
too trivial, no good use cases and examples
All of the books i bought are what I am doing on every day basis.
Mastering Spring 5.0
Unlock this book and the full library FREE for 7 days
Start now