Spring 5 Design Patterns - Dinesh Rajput - E-Book

Spring 5 Design Patterns E-Book

Dinesh Rajput

0,0
41,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Learn various design patterns and best practices in Spring 5 and use them to solve common design problems.

About This Book

  • Explore best practices for designing an application
  • Manage your code easily with Spring's Dependency Injection pattern
  • Understand the benefits that the right design patterns can offer your toolkit

Who This Book Is For

This book is for developers who would like to use design patterns to address common problems while designing an app using the Spring Framework and Reactive Programming approach. A basic knowledge of the Spring Framework and Java is assumed.

What You Will Learn

  • Develop applications using dependency injection patterns
  • Learn best practices to design enterprise applications
  • Explore Aspect-Oriented Programming relating to transactions, security, and caching.
  • Build web applications using traditional Spring MVC patterns
  • Learn to configure Spring using XML, annotations, and Java.
  • Implement caching to improve application performance.
  • Understand concurrency and handle multiple connections inside a web server.
  • Utilizing Reactive Programming Pattern to build Reactive web applications.

In Detail

Design patterns help speed up the development process by offering well tested and proven solutions to common problems. These patterns coupled with the Spring framework offer tremendous improvements in the development process.

The book begins with an overview of Spring Framework 5.0 and design patterns. You will understand the Dependency Injection pattern, which is the main principle behind the decoupling process that Spring performs, thus making it easier to manage your code. You will learn how GoF patterns can be used in Application Design. You will then learn 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. Then, you will be introduced to MVC patterns to build Reactive web applications. Finally, you will move on to more advanced topics such as Reactive streams and Concurrency.

At the end of this book, you will be well equipped to develop efficient enterprise applications using Spring 5 with common design patterns

Style and approach

The book takes a pragmatic approach, showing various design patterns and best-practice considerations, including the Reactive programming approach with the Spring 5 Framework and ways to solve common development and design problems for enterprise applications.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 421

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Spring 5 Design Patterns

 

 

 

 

 

 

 

 

 

 

 

 

Master efficient application development with patterns such as proxy, singleton, the template method, and more

 

 

 

 

 

 

 

 

 

 

 

 

Dinesh Rajput

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Spring 5 Design Patterns

 

 

Copyright © 2017 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 author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be 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: October 2017

 

Production reference: 1031017

 

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

ISBN 978-1-78829-945-9

 

www.packtpub.com

Credits

Author

Dinesh Rajput

Copy Editor

Sonia Mathur

Reviewer

Rajeev Kumar Mohan

Project Coordinator

Prajakta Naik

Commissioning Editor

Merint Mathew

Proofreader

Safis Editing

Acquisition Editor

Karan Sadawana

Indexer

Rekha Nair

ContentDevelopmentEditor

Lawrence Veigas

Graphics

Abhinash Sahu

Technical Editor

Supriya Thabe

Production Coordinator

Arvindkumar Gupta

About the Author

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture.

He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Through the course of writing this book, I contacted many people who helped me to clarify many dark corners of Reactive Patterns and GoF patterns. First of all, many thanks to the reviewer of this book, Rajeev Kumar Mohan, who is a technology consultant and trainer.
Special thanks go to Naveen Jain, who helped me create some real-world scenarios for all GoF design patterns, as mentioned in the examples.
And of course, my thanks to my lovely wife Anamika for encouraging me and supporting me in the writing of this book. Also thanks to my dear son Arnav for playing mobile games with me; it made me feel refreshed at the time of writing this book.
Finally, this book took shape from the work of Packt editors, Lawrence Veigas and Karan, who guided me through the writing process and Supriya, who joined at the last stage of the publishing process and brought many suggestions on how to make the book better and more useful for readers.

 

 

About the Reviewer

Rajeev Kumar Mohan has over 17 years of experience in IT, Software Development, and Corporate Training. He has worked for various IT majors like IBM, Pentasoft, Sapient, and Deft Infosystems. He started career as a programmer and managed various projects.

He is subject matter expert in Java, J2EE and related Frameworks, Android, and many UI Technologies. Besides SCJP and SCWCD, Rajeev has completed four masters.

He is Organic Chemistry and Computer Science master MCA and MBA. Rajeev is recruitment consultant and impaneled training consultant for HCL, Amdocs, Steria, TCS, Wipro, Oracle University, IBM, CSC, Genpact , Sapient Infosys and Capgemini.

Rajeev is the founder of Greater Noida based firm SNS Infotech. He also worked for the National Institute Of Fashion Technology [NIFT].

I would like to thank God to provide me opportunity to review the book. I would also like to thank my kids Sana and Saina and wife Nilam for their cooperation and for encouraging and allowing me to finish the review on time.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.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.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.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.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by Packt

Copy and paste, print, and bookmark content

On demand and accessible via a web browser

Customer Feedback

Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1788299450. If you'd like to join our team of regular reviewers, you can email us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

                           

I want to dedicate this book to my parents, my lovely wife, and my dear son Arnav. 
Specially dedicated to my Grand Father Late Mr. Arjun Singh

Table of Contents

Preface

What this book covers

What you need for this book

Who this book is for

Conventions

Reader feedback

Customer support

Downloading the example code

Errata

Piracy

Questions

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

Consideration of Structural and Behavioral Patterns

Examining the core design patterns

Structural design patterns

The adapter design pattern

Benefits of the adapter pattern

Common requirements for the adapter pattern

Implementation of the adapter design pattern in the Spring Framework

Sample implementation of the adapter design pattern

The Bridge design pattern

Benefits of the Bridge pattern

Common problems solved by the Bridge design pattern

Implementing the Bridge design pattern in the Spring Framework

Sample implementation of the Bridge design pattern

Composite design pattern

Common problems solved by the composite pattern

UML structure of the Composite design pattern

Sample implementation of the Composite design pattern

Decorator design pattern

Common problems solved by the Decorator pattern

Implementing the Decorator pattern

Decorator design pattern in the Spring Framework

Facade Design Pattern

Knowing when to use the Facade Pattern

Implementing the Facade design pattern

The UML structure for the Facade design pattern

Facade Pattern in the Spring Framework

Proxy design pattern

Purpose of the Proxy pattern

UML structure for the Proxy design pattern

Implementing the Proxy design pattern

Proxy pattern in the Spring Framework

Behavioral design patterns

Chain of Responsibility design pattern

Chain of Responsibility pattern in the Spring Framework

Command design pattern

Command design pattern in the Spring Framework

Interpreter Design pattern

Interpreter design pattern in the Spring Framework

Iterator Design Pattern

Iterator design pattern in the Spring Framework

Observer pattern in the Spring Framework

Template Design Pattern

JEE design patterns

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

Understanding the Bean Life Cycle and Used Patterns

The Spring bean life cycle and its phases

The initialization phase

Creating the application context from configuration

Load bean definitions

Initializing bean instances

Customizing beans using a BeanPostProcessor

The Initializer extension point

The Use phase of beans

Implementing the Decorator and Proxy patterns in Spring using Proxies

The destruction phase of the beans

Understanding bean scopes

The singleton bean scope

The prototype bean scope

The session bean scope

The request bean scope

Other scopes in Spring

Custom scopes

Creating custom scopes

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

Accessing Database with Spring ORM and Transactions Implementing Patterns

ORM Framework and the patterns used

Resource and transaction management

Consistent exception handling and translation

The data access object pattern

Creating DAOs using the Factory design pattern in Spring

The Data Mapper pattern

The domain model pattern

Proxy for the lazy loading pattern

Spring's Hibernate template pattern

Integrating Hibernate with Spring

Configuring Hibernate's SessionFactory in a Spring container

Implementing DAOs based on the plain Hibernate API

Transaction management strategies in Spring

Declarative transaction demarcation and implementation

Deploying the transaction manager

Step 1 - Implementing the transaction manager

Step 2 - Declaring the transaction demarcation

Programmatic transaction demarcation and implementation

Best practices for Spring ORM and transaction module in an application

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 the MVC Pattern in a Web Application using Spring

Implementing the MVC pattern in a web application

Model 2 architecture MVC pattern with Spring

The Front Controller design pattern

Processing the life of a request

Configuring DispatcherServlet as the Front Controller

Defined by XML configuration

Defined by Java configuration

Enabling the Spring MVC

Implementing controllers

Defining a controller with @Controller

Mapping requests with @RequestMapping

@RequestMapping at method level

@RequestMapping at the class level

Defining @RequestMapping handler methods

Passing model data to the view

Accepting request parameters

Taking query parameters

Taking request parameters via path variables

Processing forms of a web page

Implementing a form handling controller

Data binding with Command Design pattern

Using @ModelAttributes for customizing data binding

Validating forms input parameters

Implementing View in the MVC pattern

Defining ViewResolver in the Spring MVC

Implement the View

Register ViewResolver with Spring MVC

The View Helper pattern

Composite View pattern using Apache tile view resolver

Configuring a Tiles ViewResolver

Best practices for web application design

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

Preface

Spring 5 Design Patterns is for all Java developers who want to learn Spring for the enterprise application. Therefore, enterprise Java developers will find it particularly useful in the understanding of design patterns used by the Spring Framework and how it solves common design problems in the enterprise application, and they will fully appreciate the examples presented in this book. Before reading this book, readers should have basic knowledge of Core Java, JSP, Servlet, and XML.

Spring 5 Framework is newly launched by Pivotal with reactive programming. Spring 5 introduces many new features and enhancements from its previous version. We will discuss all this in the book. Spring 5 Design Patterns will give you in-depth insight about the Spring Framework.

The great part of today's Spring Framework is that all companies have already taken it as a primary framework for development of the enterprise application. For Spring, no external enterprise server is needed to start working with it.

The goals of writing this book are to discuss all design patterns used behind the Spring Framework and how they are implemented in the Spring Framework. Here, the author has also given you some best practices that must be used in the design and development of the application.

The book contains 12 chapters that cover everything from the basics to more complex design pattern such as reactive programming.

Spring 5 Design Patterns is divided into three sections. The first section introduces you to the essentials of the design patterns and the Spring Framework. The second section steps behind the front end and shows where Spring fits in the back end of an application. The third section expands on this by showing how to build web applications with Spring and introducing a new feature of the Spring 5 reactive programming. This part also shows how to handle concurrency in the enterprise application.

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, Consideration of the Structural and the Behavioural Patterns, gives an overview of the Structural and Behavioural 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 problem solving with design patterns.

Chapter 4, 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 5, Understanding the Bean Life cycle and Used Patterns, gives an overview of Spring Bean Life cycle managed by the Spring container, including an understanding of Spring containers and IoC. You'll also get an overview of the Spring bean life cycle callback handlers and post processors.

Chapter 6, 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 7, Accessing Database with Spring and JDBC Template Pattern, 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 8, Accessing Database with Spring ORM and Transactions Implementing Patterns, shows how Spring integrates with the ORM Frameworks, such as Hibernate and other implementations of the Java Persistence API (JPA) with Spring Transaction Management. Also, this contains magic provided by Spring Data JPA for on-the-fly queries generation.

Chapter 9, Improving Performance of Application 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 10, Implementing MVC Pattern in a Web Application using Spring, gives a quick overview of developing a web application with the Spring MVC. You'll learn the MVC pattern, Front Controller pattern, Dispatcher Servlet with the basics of Spring MVC, a web framework built on the principles of the Spring Framework. You'll discover how to write controllers to handle web requests and see how to transparently bind request parameters and payload to your business objects while providing validation and error handling at the same time. This chapter also gives a brief introduction to view and view resolver in the Spring MVC.

Chapter 11, Implementing Reactive Design Pattern, 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 12, 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.

What you need for 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.

Who this book is for

Spring 5 Design Patterns is for all Java developers who want to learn Spring for the enterprise application. Therefore, enterprise Java developers will find it particularly useful in the understanding of design patterns used by Spring Framework and how it solves common design problems in the enterprise application, and they will fully appreciate the examples presented in this book. Before reading this book, readers should have basic knowledge of Core Java, JSP, Servlet, and XML.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book--what you liked or disliked. Reader feedback is important to us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply email [email protected], and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.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 to our website using your email address and password.

Hover the mouse pointer on the

SUPPORT

tab at the top.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box.

Select the book for which you're looking to download the code files.

Choose from the drop-down menu where you purchased this book from.

Click on

Code Download

.

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/Spring5-Design-Patterns. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books--may be a mistake in the text or the code--we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

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 you in unit testing these classes independently.