Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Discover millions of ebooks, audiobooks, and so much more with a free trial

From $11.99/month after trial. Cancel anytime.

Building Microservices with Spring: Master design patterns of the Spring framework to build smart, efficient microservices
Building Microservices with Spring: Master design patterns of the Spring framework to build smart, efficient microservices
Building Microservices with Spring: Master design patterns of the Spring framework to build smart, efficient microservices
Ebook865 pages6 hours

Building Microservices with Spring: Master design patterns of the Spring framework to build smart, efficient microservices

Rating: 0 out of 5 stars

()

Read preview

About this ebook

Learn and use the design patterns and best practices in Spring to solve common design problems and build user-friendly microservices

Key Features
  • Study the benefits of using the right design pattern in your toolkit
  • Manage your code easily with Spring's dependency injection pattern
  • Explore the features of Docker and Mesos to build successful microservices
Book Description

Getting Started with Spring Microservices begins with an overview of the Spring Framework 5.0, its design patterns, and its guidelines that enable you to implement responsive microservices at scale. You will learn how to use GoF patterns in application design. You will understand the dependency injection pattern, which is the main principle behind the decoupling process of the Spring Framework and makes it easier to manage your code. Then, you will learn how to use proxy patterns in aspect-oriented programming and remoting. Moving on, you will understand the JDBC template patterns and their use in abstracting database access.

After understanding the basics, you will move on to more advanced topics, such as reactive streams and concurrency. Written to the latest specifications of Spring that focuses on Reactive Programming, the Learning Path teaches you how to build modern, internet-scale Java applications in no time.

Next, you will understand how Spring Boot is used to deploying serverless autonomous services by removing the need to have a heavyweight application server. You’ll also explore ways to deploy your microservices to Docker and managing them with Mesos.

By the end of this Learning Path, you will have the clarity and confidence for implementing microservices using Spring Framework.

This Learning Path includes content from the following Packt products:

  • Spring 5 Microservices by Rajesh R V
  • Spring 5 Design Patterns by Dinesh Rajput
What you will learn
  • Develop applications using dependency injection patterns
  • Build web applications using traditional Spring MVC patterns
  • Utilize the reactive programming pattern to build reactive web apps
  • Learn concurrency and handle multiple connections inside a web server
  • Use Spring Boot and Spring Cloud to develop microservices
  • Leverage reactive programming to build cloud-native applications
Who this book is for

Getting Started with Spring Microservices is ideal for Spring developers who want to use design patterns to solve common design problems and build cloud-ready, Internet-scale applications, and simple RESTful services.

Rajesh R V is a seasoned IT architect with extensive experience in diversified technologies and more than 18 years of airline IT experience. He received a degree in computer engineering from the University of Cochin, India, and he joined the JEE community during the early days of EJB. During his course as an architect, he worked on many large-scale, mission-critical projects, including the new generation Passenger Reservation System (iFly Res) and next generation Cargo Reservation System (Skychain, CROAMIS) in the Airline domain. At present, as a chief architect at Emirates, Rajesh handles the solution architecture portfolio spread across various capabilities, such as JEE, SOA, NoSQL, IoT, cognitive computing, mobile, UI, and integration. At Emirates, the Open Travel Platform (OTP) architected by him earned the group the prestigious 2011 Red Hat Innovation Award in the Carved Out Costs category. In 2011, he introduced the innovative concept of the Honeycomb architecture based on the hexagonal architecture pattern for transforming the legacy mainframe system. Rajesh has a deep passion for technology and architecture. He also holds several certifications, such as BEA Certified Weblogic Administrator, Sun Certified Java Enterprise Architect, Open Group Certified TOGAF practitioner, Licensed ZapThink Archi
LanguageEnglish
Release dateDec 21, 2018
ISBN9781789958188
Building Microservices with Spring: Master design patterns of the Spring framework to build smart, efficient microservices

Read more from Dinesh Rajput

Related to Building Microservices with Spring

Related ebooks

Programming For You

View More

Related articles

Reviews for Building Microservices with Spring

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Building Microservices with Spring - Dinesh Rajput

    Learning Path - Getting started with Spring Microservices

    Building Microservices

    with Spring

    Master design patterns of the Spring framework to build smart, efficient microservices

    Dinesh Rajput

    Rajesh R V

    BIRMINGHAM - MUMBAI

    Building Microservices with Spring

    Copyright © 2018 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

    Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

    First published: December 2018

    Production reference: 1181218

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham

    B3 2PB, UK.

    ISBN 978-1-78995-564-4

    www.packtpub.com

    mapt.io

    Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

    Why subscribe?

    Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

    Improve your learning with Skill Plans built especially for you

    Get a free eBook or video every month

    Mapt is fully searchable

    Copy and paste, print, and bookmark content

    Packt.com

    Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at customercare@packtpub.com for more details.

    At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks. 

    Contributors

    About the authors

    Dinesh Rajput is a founder of Dineshonjava (dot) com, a blog for Spring and Java techies. He is a Spring enthusiast and a Pivotal Certified Spring Professional. He has written two bestselling books, Spring 5 Design Patterns and Mastering Spring Boot 2.0. Mastering Spring Boot 2.0 is the Amazon #1 best-selling book on Java. He has more than 10 years of experience with various aspects of Spring and cloud-native development, such as REST APIs and microservice architecture. He is currently working as an architect at a leading company. He has worked as a tech lead at Bennett, Coleman & Co. Ltd, and Paytm. He has a master's degree in computer engineering from JSS Academy of Technical Education, Noida, and lives in Noida with his family.

    Rajesh R V is a seasoned IT architect with extensive experience in diversified technologies and more than 18 years of airline IT experience.

    He received a degree in computer engineering from the University of Cochin, India, and he joined the JEE community during the early days of EJB. During his course as an architect, he worked on many large-scale, mission-critical projects, including the new generation Passenger Reservation System (iFly Res) and next generation Cargo Reservation System (Skychain, CROAMIS) in the Airline domain.

    At present, as a chief architect at Emirates, Rajesh handles the solution architecture portfolio spread across various capabilities, such as JEE, SOA, NoSQL, IoT, cognitive computing, mobile, UI, and integration. At Emirates, the Open Travel Platform (OTP) architected by him earned the group the prestigious 2011 Red Hat Innovation Award in the Carved Out Costs category. In 2011, he introduced the innovative concept of the Honeycomb architecture based on the hexagonal architecture pattern for transforming the legacy mainframe system.

    Rajesh has a deep passion for technology and architecture. He also holds several certifications, such as BEA Certified Weblogic Administrator, Sun Certified Java Enterprise Architect, Open Group Certified TOGAF practitioner, Licensed ZapThink Architect in SOA, and IASA global CITA-A Certified Architecture Specialist.

    He has written Spring Microservices and reviewed Service-Oriented Java Business Integration by Packt Publishing.

    Packt is searching for authors like you

    If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

    Table of Contents

    Title Page

    Copyright

    Building Microservices with Spring

    About Packt

    Why subscribe?

    Packt.com

    Contributors

    About the authors

    Packt is searching for authors like you

    Preface

    Who this book is for

    What this book covers

    To get the most out of this book

    Download the example code files

    Conventions used

    Get in touch

    Reviews

    Getting Started with Spring Framework 5.0 and Design Patterns

    Introducing Spring Framework

    Simplifying application development using Spring and its pattern

    Using the power of the POJO pattern

    Injecting dependencies between POJOs

    How DI works and makes things easy for development and testing

    Using factory helper pattern for dependent components

    Using DI pattern for dependent components

    Applying aspects for cross cutting concerns

    How Spring AOP works

    Applying the template pattern to eliminate boilerplate code

    The Template Design pattern in Spring

    Using a Spring container to manage beans with the Factory pattern

    Bean factory

    Application contexts

    Creating a container with an application context

    Life of a bean in the container

    Spring modules

    Core Spring container

    Spring's AOP module

    Spring DAO - data access and integration

    Spring's ORM

    Spring web MVC

    New features in Spring Framework 5.0

    Summary

    Overview of GOF Design Patterns - Core Design Patterns

    Introducing the power of design patterns

    Common GoF Design Pattern overview

    Creational design patterns

    Factory design pattern

    Implementing the Factory design pattern in Spring Framework

    Sample implementation of the Factory design pattern

    Abstract factory design pattern

    Common problems where you should apply the Abstract factory design pattern

    Implementing the Abstract factory design pattern in the Spring Framework

    Sample implementation of the Abstract Factory design pattern

    Singleton design pattern

    Common problems where you should apply Singleton pattern

    Singleton design pattern implementation in the Spring Framework

    Sample implementation of the Singleton design pattern

    Prototype design pattern

    Benefits of the Prototype design pattern

    UML class structure

    Sample implementation of the Prototype design pattern

    Builder design pattern

    Benefits of the Builder pattern:

    UML class structure

    Implementing the Builder pattern in the Spring Framework

    Common problems where you should apply Builder pattern

    Sample implementation of the Builder design pattern

    Summary

    Wiring Beans using the Dependency Injection Pattern

    The dependency injection pattern

    Solving problems using the dependencies injection pattern

    Without dependency injection

    With dependency injection pattern

    Types of dependency injection patterns

    Constructor-based dependency injection pattern

    Setter-based dependency injection

    Configuring the dependency injection pattern with Spring

    Dependency injection pattern with Java-based configuration

    Creating a Java configuration class - AppConfig.java

    Declaring Spring beans into configuration class

    Injecting Spring beans

    Best approach to configure the dependency injection pattern with Java

    Dependency injection pattern with XML-based configuration

    Creating an XML configuration file

    Declaring Spring beans in an XML file

    Injecting Spring beans

    Using constructor injection

    Using setter injection

    Dependency injection pattern with Annotation-based configuration

    What are Stereotype annotations?

    Creating auto searchable beans using Stereotype annotations

    Searching beans using component scanning

    Annotating beans for autowiring

    Using @Autowired with setter method

    Using @Autowired with the fields

    The Autowiring DI pattern and disambiguation

    Resolving disambiguation in Autowiring DI pattern

    Implementing the Abstract Factory Pattern in Spring (FactoryBean interface)

    Implementation of FactoryBean interface in Spring

    Sample implementation of FactoryBean interface

    Best practices for configuring the DI pattern

    Summary

    Spring Aspect Oriented Programming with Proxy and Decorator pattern

    Proxy pattern in Spring

    Proxying classes using Decorator pattern in Spring

    What are cross-cutting concerns?

    What is Aspect-Oriented Programming?

    Problems resolved by AOP

    Code tangling

    Code scattering

    How AOP Works to solve problems

    Core AOP terminology and concepts

    Advice

    Join Point

    Pointcut

    Aspect

    Weaving

    Defining pointcuts

    Writing pointcuts

    Creating aspects

    Define aspects using Annotation

    Implementing Advice

    Advice type - Before

    Before Advice example

    Advice Types: After Returning

    After Returning Advice example

    Advice Types: After Throwing

    After Throwing Advice example

    Advice Types: After

    After Advice example

    Advice Types - Around

    Around Advice example

    Define aspects using XML configuration

    Understanding AOP proxies

    Summary

    Accessing a Database with Spring and JDBC Template Patterns

    The best approach to designing your data-access

    The resource management problem

    Implementing the template design pattern

    Problems with the traditional JDBC

    Solving problems with Spring's JdbcTemplate

    Configuring the data source and object pool pattern

    Configuring a data source using a JDBC driver

    Configuring the data source using pool connections

    Implementing the Builder pattern to create an embedded data source

    Abstracting database access using the DAO pattern

    The DAO pattern with the Spring Framework

    Working with JdbcTemplate

    When to use JdbcTemplate

    Creating a JdbcTemplate in an application

    Implementing a JDBC-based repository

    Jdbc callback interfaces

    Creating a RowMapper class

    Implementing RowCallbackHandler

    Implementing ResultSetExtractor

    Best practices for Jdbc and configuring JdbcTemplate

    Summary

    Improving Application Performance Using Caching Patterns

    What is cache?

    Where do we use caching?

    Understanding cache abstraction

    Enabling caching via the Proxy pattern

    Enabling the caching proxy using Annotation

    Enabling the Caching Proxy using the XML namespace

    Declarative Annotation-based caching

    The @Cacheable annotation

    The @CachePut annotation

    Customizing the cache key

    Conditional caching

    The @CacheEvict annotation

    The @Caching annotation

    The @CacheConfig annotation

    Declarative XML-based caching

    Configuring the cache storage

    Setting up the CacheManager

    Third-party cache implementations

    Ehcache-based cache

    XML-based configuration

    Creating custom caching annotations

    Top caching best practices to be used in a web application

    Summary

    Implementing Reactive Design Patterns

    Understanding application requirement over the years

    Understanding the reactive pattern

    The reactive pattern traits

    Responsiveness

    Resilience

    Scalable

    Message-driven architecture

    Blocking calls

    Non-blocking calls

    Back-pressure

    Implementing reactive with the Spring 5 Framework

    Reactive Streams

    Spring Web reactive module

    Implementing a reactive web application at the server side

    The Annotation-based programming model

    The functional programming model

    Implementing a Reactive Client-Side application

    Request and response body conversion

    Summary

    Implementing Concurrency Patterns

    Active object pattern

    Monitor object pattern

    Half-Sync/Half-Async patterns

    Leader/follower pattern

    Reactor pattern

    Thread-specific storage pattern

    Best practices for concurrency module

    Summary

    Demystifying Microservices

    Evolution of microservices

    Business demand as a catalyst for microservices evolution

    Technology as a catalyst for microservices evolution

    Imperative architecture evolution

    What are Microservices?

    Microservices - The honeycomb analogy

    Principles of microservices

    Single responsibility per service

    Microservices are autonomous

    Characteristics of microservices

    Services are first class citizens

    Characteristics of service in a microservice

    Microservices are lightweight

    Microservices with polyglot architecture

    Automation in microservices environment

    Microservices with a supporting ecosystem

    Microservices are distributed and dynamic

    Antifragility, fail fast, and self healing

    Microservices examples

    An example of a holiday portal

    An example of a travel agent portal

    Microservices benefits

    Supports polyglot architecture

    Enables experimentation and innovation

    Elastically and selectively scalable

    Allows substitution

    Enables to build organic systems

    Helps managing technology debt

    Allowing co-existence of different versions

    Supporting building self-organizing systems

    Supporting event-driven architecture

    Enables DevOps

    Summary

    Related Architecture Styles and Use Cases

    Service-Oriented Architecture (SOA)

    Service-oriented integration

    Legacy modernization

    Service-oriented application

    Monolithic migration using SOA

    Twelve-Factor Apps

    Single code base

    Bundle dependencies

    Externalizing configurations

    Backing services are addressable

    Isolation between build, release, and run

    Stateless, shared nothing processes

    Expose services through port bindings

    Concurrency for scale out

    Disposability, with minimal overhead

    Development, production parity

    Externalizing logs

    Package admin processes

    Serverless computing

    Lambda architecture

    DevOps, Cloud, and Containers

    DevOps as the practice and process for microservices

    Cloud and Containers as the self-service infrastructure for microservices

    Reactive microservices

    A reactive microservice-based order management system

    Microservice use cases

    Microservices early adopters - Is there a common theme?

    Monolithic migration as the common use case

    Microservice frameworks

    Summary

    Building Microservices with Spring Boot

    Setting up a development environment

    Spring Boot for building RESTful microservices

    Getting started with Spring Boot

    Developing a Spring Boot microservice

    Developing our first Spring Boot microservice

    Testing Spring Boot microservice

    HATEOAS-enabled Spring Boot microservice

    Reactive Spring Boot microservices

    Reactive microservices using Spring WebFlux

    Understanding Reactive Streams

    Publisher

    Subscriber

    Subscription

    Processor

    Reactive microservices using Spring Boot and RabbitMQ

    Implementing security

    Securing a microservice with basic security

    Securing microservice with OAuth2

    Enabling cross origin for microservices interactions

    Spring Boot actuators for microservices instrumentation

    Monitoring using JConsole

    Monitoring using ssh

    Adding a custom health module

    Building custom metrics

    Documenting microservices

    Putting it all together - Developing a customer registration microservice example

    Summary

    Scale Microservices with Spring Cloud Components

    What is Spring Cloud?

    Spring Cloud releases

    Setting up the environment for the BrownField PSS

    Spring Cloud Config

    Building microservices with Config Server

    Setting up the Config Server

    Understanding the Config Server URL

    Accessing the Config Server from clients

    Handling configuration changes

    Spring Cloud Bus for propagating configuration changes

    Setting up high availability for the Config Server

    Monitoring Config Server health

    Config Server for configuration files

    Completing changes to use Config Server

    Eureka for registration and discovery

    Understanding dynamic service registration and discovery

    Understanding Eureka

    Setting up the Eureka Server

    High availability for Eureka

    Zuul proxy as the API Gateway

    Setting up Zuul

    High availability of Zuul

    High availability of Zuul when the client is also a Eureka Client

    High availability when client is not a Eureka Client

    Completing Zuul for all other services

    Streams for reactive microservices

    Protecting microservices with Spring Cloud Security

    Summarising the BrownField PSS architecture

    Summary

    Logging and Monitoring Microservices

    Understanding log management challenges

    Centralized logging solution

    Selection of logging solutions

    Cloud services

    Off-the-shelf solutions

    Best of the breed integration

    Log shippers

    Log stream processors

    Log storage

    Dashboards

    Custom logging implementation

    Distributed tracing with Spring Cloud Sleuth

    Monitoring microservices

    Monitoring challenges

    Monitoring tools

    Monitoring microservice dependency

    Spring Cloud Hystrix for fault-tolerant microservices

    Aggregate Hystrix streams with Turbine

    Data analysis using Data Lake

    Summary

    Containerizing Microservices with Docker

    Understanding gaps in the BrownField PSS microservices

    What are containers?

    Difference between VM and containers

    Benefits of containers

    Microservices and containers

    Introduction to Docker

    Key components of Docker

    The Docker daemon

    The Docker client

    The Docker image

    The Docker container

    The Docker registry

    Dockerfile

    Deploying microservices into Docker

    Running RabbitMQ on Docker

    Using the Docker registry

    Setting up the Docker Hub

    Publish microservices to the Docker Hub

    Microservices on Cloud

    Installing Docker on AWS EC2

    Running BrownField services on EC2

    Future of containerization

    Summary

    Scaling Dockerized Microservices with Mesos and Marathon

    Scaling microservices

    Understanding autoscaling

    The missing pieces

    Container orchestration

    Why is container orchestration is important

    What does container orchestration do?

    Relationship with microservices

    Relationship with virtualization

    Container orchestration solutions

    Docker Swarm

    Kubernetes

    Apache Mesos

    HashiCorp Nomad

    CoreOS Fleet

    Container orchestration with Mesos and Marathon

    Mesos in details

    Mesos architecture

    Marathon

    Implementing Mesos and Marathon with DCOS

    Implementing Mesos and Marathon for BrownField microservices

    Installing Mesos, Marathon, and related components

    Running Mesos and Marathon

    Preparing BrownField PSS services

    Deploying BrownField PSS services

    Summary

    Other Books You May Enjoy

    Leave a review - let other readers know what you think

    Preface

    Getting Started with Spring Microservices begins with an overview of the Spring Framework 5.0, its design patterns, and its guidelines that enable you to implement responsive microservices at scale. You will learn how to use GoF patterns in application design. You will understand the dependency injection pattern, which is the main principle behind the decoupling process of the Spring Framework and makes it easier to manage your code. Then, you will learn how to use proxy patterns in aspect-oriented programming and remoting. Moving on, you will understand the JDBC template patterns and their use in abstracting database access.

    After understanding the basics, you will move on to more advanced topics, such as reactive streams and concurrency. Written to the latest specifications of Spring that focuses on Reactive Programming, the Learning Path teaches you how to build modern, internet-scale Java applications in no time.

    Next, you will understand how Spring Boot is used to deploying serverless autonomous services by removing the need to have a heavyweight application server. You’ll also explore ways to deploy your microservices to Docker and managing them with Mesos.

    By the end of this Learning Path, you will have the clarity and confidence for implementing microservices using Spring Framework.

    This Learning Path includes content from the following Packt products:

    • Spring 5 Microservices by Rajesh R V

    • Spring 5 Design Patterns by Dinesh Rajput

    Who this book is for

    Getting Started with Spring Microservices is ideal for Spring developers who want to use design patterns to solve common design problems and build cloud-ready, Internet-scale applications, and simple RESTful services.

    What this book covers

    Chapter 1, Getting Started with the Spring Framework 5.0 and Design Patterns, gives an overview of the Spring 5 Framework and all new features of the Spring 5 Framework, including some basic examples of DI and AOP. You’ll also get an overview of the great

    Spring portfolio.

    Chapter 2, Overview of GOF Design Patterns - Core Design Patterns, gives an overview of the Core Design Pattern of the GoF Design Patterns family, including some best practices for an application design. You'll also get an overview of the common problems solving with design patterns.

    Chapter 3, Wiring Beans using Dependency Injection Pattern, explores dependency injection pattern and detail about the configuration of Spring in an application, showing you various ways of configurations in your application. This includes a configuration with XML, Annotation, Java, and Mix.

    Chapter 4, Spring Aspect Oriented Programming with Proxy and Decorator Pattern, explores how to use Spring AOP to decouple cross-cutting concerns from the objects that they service. This chapter also sets the stage for later chapters where you'll use AOP to provide declarative services such as transactions, security, and caching.

    Chapter 5, Accessing Database with Spring and JDBC Template Patterns, explores how to access the data with Spring and JDBC; here, you’ll see how to use Spring's JDBC abstraction and JDBC Template to query relational databases in a way that is far simpler than native JDBC.

    Chapter 6, Improving Application Performance Using Caching Patterns, shows how to improve application performance by avoiding the database altogether if the data needed is readily available. So, I will show you how Spring provides support for caching data.

    Chapter 7, Implementing Reactive Design Patterns, explores the Reactive Programming Model, which is programming with asynchronous data streams. You'll see how the Reactive System is implemented in the Spring Web Module.

    Chapter 8, Implementing Concurrency Patterns, takes a closer look at concurrency when handling multiple connections inside a web server. As outlined in our architectural model, request handling is decoupled from application logic.

    Chapter 9, Demystifying Microservices, gives you an introduction to microservices. This chapter covers the background, evaluation, and fundamental concepts of microservices.

    Chapter 10, Related Architecture Styles and Use Cases, covers the relationship with Service-Oriented Architecture, the concepts of cloud native and Twelve Factor applications, and explains some of the common use cases.

    Chapter 11, Building Microservices with Spring Boot, introduces building REST and message-based microservices using the Spring Framework and how to wrap them with Spring Boot. In addition, we will also explore some core capabilities of Spring Boot.

    Chapter 12, Scale Microservices with Spring Cloud Components, shows you how to scale previous examples using Spring Cloud stack capabilities. It details the architecture and different components of Spring Cloud and how they integrate together.

    Chapter 13, Logging and Monitoring Microservices, covers the importance of logging and monitoring aspects when developing microservices. Here, we look at the details of some of the best practices when using microservices, such as centralized logging and monitoring capabilities using open source tools and how to integrate them with Spring projects.

    Chapter 14, Containerizing Microservices with Docker, explains containerization concepts in the context of microservices. Using Mesos and Marathon, it demonstrates next-level implementation to replace the custom life cycle manager for large deployments.

    Chapter 15, Scaling Dockerized Microservices with Mesos and Marathon, explains auto-provisioning and deployment of microservices. Here, we will also learn how to use Docker containers in the preceding example for large-scale deployments.

    To get the most out of this book

    This book can be read without a computer or laptop at hand, in which case you need nothing more than the book itself. Although to follow the examples in the book, you need Java 8, which you can download from http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html. You will also need your favorite IDE for the examples, but I have used the Software Spring Tool Suite; download the latest version of Spring Tool Suite (STS) from https://spring.io/tools/sts/all according to your system OS. The Java 8 and STS work on a variety of platforms--Windows, macOS, and Linux.

    Other software components required are as follows:

    Spring Cloud Dalston RELEASE

    elasticsearch-1.5.2

    kibana-4.0.2-darwin-x64

    logstash-2.1.2

    Docker version (17.03.1-ce)

    Docker Hub

    Mesos version 1.2.0

    Docker version 17.03.1-ce

    Marathon version 3.4.9

    Download the example code files

    You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.

    You can download the code files by following these steps:

    Log in or register at www.packt.com.

    Select the SUPPORT tab.

    Click on Code Downloads & Errata.

    Enter the name of the book in the Search box and follow the onscreen instructions.

    Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

    WinRAR/7-Zip for Windows

    Zipeg/iZip/UnRarX for Mac

    7-Zip/PeaZip for Linux

    The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Building-Microservices-with-Spring. In case there's an update to the code, it will be updated on the existing GitHub repository.

    We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

    Conventions used

    There are a number of text conventions used throughout this book.

    CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: The EventEmitter object is defined in the events module of Node.js.

    A block of code is set as follows:

    if (anotherNote instanceof Note) {

    ... it's a Note, so act on it as a Note

    }

    Any command-line input or output is written as follows:

    $ npm update express

    $ npm update

    Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "If you need something different, click on the DOWNLOADS link in the header for all possible downloads: "

    Warnings or important notes appear like this.

    Tips and tricks appear like this.

    Get in touch

    Feedback from our readers is always welcome.

    General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at customercare@packtpub.com.

    Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

    Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at copyright@packt.com with a link to the material.

    If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

    Reviews

    Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

    For more information about Packt, please visit packt.com.

    Getting Started with Spring Framework 5.0 and Design Patterns

    This chapter will help you gain a better understanding of the Spring Framework with modules, and use the design patterns that are responsible for the success of Spring. This chapter will cover every major module of the Spring Framework. We begin with an introduction to the Spring Framework. We will have a look at the new features and enhancement introduced in Spring 5. We will also understand the design patterns used in the major modules of the Spring Framework.

    At the end of this chapter, you will understand how Spring works, and how Spring solves the common problems of the design level of the enterprise application by using design patterns. You will know how to improve loose coupling between the components of applications and how to simplify application development by using Spring with design patterns.

    This chapter will cover the following topics:

    Introduction of the Spring Framework

    Simplifying application development using Spring and its pattern

    Using the power of the POJO pattern

    Injecting dependencies

    Applying aspects to address cross-cutting concerns

    Applying a template pattern to eliminate boilerplate code

    Creating a Spring container for containing beans using the Factory pattern

    Creating a container with an application context

    The life of a bean in the container

    Spring modules

    New features in Spring Framework 5.0

    Introducing Spring Framework

    In the early days of Java, there were lots of heavier enterprise Java technologies for enterprise applications that provided enterprise solutions to programmers. However, it was not easy to maintain the applications because it was tightly coupled with the framework. A couple of years ago, apart from Spring, all Java technologies were heavier, like EJB. At the time, Spring was introduced as an alternative technology especially made for EJB because Spring provided a very simple, leaner, and lighter programming model compared with other existing Java technologies. Spring makes this possible by using many available design patterns, but it focused on the Plain Old Java Object (POJO) programming model. This model provided the simplicity to the Spring Framework. It also empowered ideas such as the dependency injection (DI) pattern and Aspect-Oriented Programming (AOP) by using the Proxy pattern and Decorator pattern.

    The Spring Framework is an open source application framework and a Java-based platform that provides comprehensive infrastructure support for developing enterprise Java applications. So developers don't need to care about the infrastructure of the application; they should be focused on the business logic of the application rather than handling the configuration of the application. All infrastructure, configuration, and meta-configuration files, either Java-based configuration or XML-based configuration, both are handled by the Spring Framework. So this framework makes you more flexible in building an application with a POJOs programming model rather than a non-invasive programming model.

    The Spring Inversion of Control (IoC) container is the heart of the entire framework. It helps glue together the different parts of the application, thus forming a coherent architecture. Spring MVC components can be used to build a very flexible web tier. The IOC container simplifies the development of the business layer with POJOs.

    Spring simplifies the application development and removes a lot of the dependency on the other APIs. Let's see some examples of how you, as an application developer, can benefit from the Spring platform:

    All application classes are simple POJO classes--Spring is not invasive. It does not require you to extend framework classes or implement framework interfaces for most use cases.

    Spring applications do not require a Java EE application server, but they can be deployed on one.

    You can execute a method in a database transaction by using transaction management in Spring Framework without having any third-party transactional API.

    Using Spring, you can use a Java method as a request handler method or remote method, like a service() method of a servlet API, but without dealing with the servlet API of the servlet container.

    Spring enables you to use a local java method as a message handler method without using a Java Message Service (JMS) API in the application.

    Spring also enables you to use the local java method as a management operation without using a Java Management Extensions (JMX) API in the application.

    Spring serves as a container for your application objects. Your objects do not have to worry about finding and establishing connections with each other.

    Spring instantiates the beans and injects the dependencies of your objects into the application--it serves as a life cycle manager of the beans.

    Simplifying application development using Spring and its pattern

    Developing an enterprise application using the traditional Java platform has a lot of limitations when it comes to organizing the basic building blocks as individual components for reusability in your application. Creating reusable components for basic and common functionality is best design practice, so you cannot ignore it. To address the reusability problem in your application, you can use various design patterns, such as the Factory pattern, Abstract Factory pattern, Builder pattern, Decorator pattern, and Service Locator pattern, to compose the basic building blocks into a coherent whole, such as class and object instances, to promote the reusability of components. These patterns address the common and recursive application problems. Spring Framework simply implements these patterns internally, providing you with an infrastructure to use in a formalized way.

    There are lots of complexities in enterprise application development, but Spring was created to address these, and makes it possible to simplify the process for developers. Spring isn't only limited to server-side development--it also helps simplifies things regarding building projects, testability, and loose coupling. Spring follows the POJO pattern, that is, a Spring component can be any type of POJO. A component is a self-contained piece of code that ideally could be reused in multiple applications.

    Since this book is focused on all design patterns that are adopted by the Spring Framework to simplify Java development, we need to discuss or at least provide some basic implementation and consideration of design patterns and the best practices to design the infrastructure for enterprise application development. Spring uses the following strategies to make java development easy and testable:

    Spring uses the power of the POJO pattern for lightweight and minimally invasive development of enterprise applications

    It uses the power of the dependency injection pattern (DI pattern) for loose coupling and makes a system interface oriented

    It uses the power of the Decorator and Proxy design pattern for declarative programming through aspects and common conventions

    It uses the power of the Template Design pattern for eliminating boilerplate code with aspects and templates

    In this chapter, I'll explain each of these ideas, and also show concrete examples of how Spring simplifies Java development. Let's start with exploring how Spring remains minimally invasive by encouraging POJO-oriented development by using the POJO pattern.

    Using the power of the POJO pattern

    There are many other frameworks for Java development that lock you in by forcing you to extend or implement one of their existing classes or interfaces; Struts, Tapestry, and earlier versions of EJB had this approach. The programming model of these frameworks is based on the invasive model. This makes it harder for your code to find bugs in the system, and sometimes it will render your code unintelligible. However, if you are working with Spring Framework, you don't need to implement or extend its existing classes and interfaces, so this is simply POJO-based implementation, following a non-invasive programming model. It makes it easier for your code to find bugs in the system, and keeps the code understandable.

    Spring allows you to do programming with very simple non Spring classes, which means there is no need to implement Spring-specific classes or interfaces, so all classes in the Spring-based application are simply POJOs. That means you can compile and run these files without dependency on Spring libraries; you cannot even recognize that these classes are being used by the Spring Framework. In Java-based configuration, you will use Spring annotations, which is the worst case of the Spring-based application.

    Let's look at this with the help of the following example:

        package com.packt.chapter1.spring;

        public class HelloWorld {

          public String hello() {

            return Hello World;

          }

        }

    The preceding class is a simple POJO class with no special indication or implementation related to the framework to make it a Spring component. So this class could function equally well in a Spring application as it could in a non-Spring application. This is the beauty of Spring's non-invasive programming model. Another way that Spring empowers POJO is by collaborating with other POJOs using the DI pattern. Let's see how DI works to help decouple components.

    Injecting dependencies between POJOs

    The term dependency injection is not new-it is used by PicoContainer. Dependency injection is a design pattern that promotes loose coupling between the Spring components--that is, between the different collaborating POJOs. So by applying DI to your complex programming, your code will become simpler, easier to understand, and easier to test.

    In your application, many objects are working together for a particular functionality as per your requirement. This collaboration between the objects is actually known as dependency injection. Injecting dependency between the working components helps you to unit test every component in your application without tight coupling.

    In a working application, what the end user wants is to see the output. To create the output, a few objects in the application work together and are sometimes coupled. So when you are writing these complex application classes, consider the reusability of these classes and make these classes as independent as possible. This is a best practice of coding that will help

    Enjoying the preview?
    Page 1 of 1