Java 9 Dependency Injection - Nilang Patel - E-Book

Java 9 Dependency Injection E-Book

Nilang Patel

0,0
35,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

Create clean code with Dependency Injection principles

Key Features

  • Use DI to make your code loosely coupled to manage and test your applications easily on Spring 5 and Google Guice
  • Learn the best practices and methodologies to implement DI
  • Write more maintainable Java code by decoupling your objects from their implementations

Book Description

Dependency Injection (DI) is a design pattern that allows us to remove the hard-coded dependencies and make our application loosely coupled, extendable, and maintainable. We can implement DI to move the dependency resolution from compile-time to runtime. This book will be your one stop guide to write loosely coupled code using the latest features of Java 9 with frameworks such as Spring 5 and Google Guice.

We begin by explaining what DI is and teaching you about IoC containers. Then you’ll learn about object compositions and their role in DI. You’ll find out how to build a modular application and learn how to use DI to focus your efforts on the business logic unique to your application and let the framework handle the infrastructure work to put it all together.

Moving on, you’ll gain knowledge of Java 9’s new features and modular framework and how DI works in Java 9. Next, we’ll explore Spring and Guice, the popular frameworks for DI. You’ll see how to define injection keys and configure them at the framework-specific level. After that, you’ll find out about the different types of scopes available in both popular frameworks. You’ll see how to manage dependency of cross-cutting concerns while writing applications through aspect-oriented programming.

Towards the end, you’ll learn to integrate any third-party library in your DI-enabled application and explore common pitfalls and recommendations to build a solid application with the help of best practices, patterns, and anti-patterns in DI.

What you will learn

  • Understand the benefits of DI and fo from a tightly coupled design to a cleaner design organized around dependencies
  • See Java 9’s new features and modular framework
  • Set up Guice and Spring in an application so that it can be used for DI
  • Write integration tests for DI applications
  • Use scopes to handle complex application scenarios
  • Integrate any third-party library in your DI-enabled application
  • Implement Aspect-Oriented Programming to handle common cross-cutting concerns such as logging, authentication, and transactions
  • Understand IoC patterns and anti-patterns in DI

Who this book is for

This book is for Java developers who would like to implement DI in their application. Prior knowledge of the Spring and Guice frameworks and Java programming is assumed.

Krunal Patel has been working at Liferay Portal for over 5 years and has over 9 years of experience in enterprise application development using Java and Java EE technologies. He has worked in various domains, such as healthcare, hospitality, and enterprise intranet. He was awarded an ITIL® Foundation Certificate in IT Service Management in 2015, a Liferay 6.1 Developer Certification in 2013, and a MongoDB for Java Developers certificate in 2013. He has reviewed Mastering Apache Solr 7.x by Packt Publishing. Nilang Patel has over 14 years of core IT experience in leading project, software design and development, and supporting enterprise applications using enterprise Java technologies. He is experienced in core Java/J2EE based application and has experience in healthcare, human resource, taxation, intranet application, energy and risk management domain. He contributes to various forums and has a personal blog. He acquired the Liferay 6.1 Developer Certification in 2013, Brainbench Java 6 certification in 2012, and a Sun Certified Programmer for the Java 2 Platform 1.5 (SCJP) in 2007.

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

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 254

Veröffentlichungsjahr: 2018

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.



Java 9 Dependency Injection

 

 

 

 

 

 

 

 

 

 

 

Write loosely coupled code with Spring 5 and Guice

 

 

 

 

 

 

 

 

 

 

 

Krunal Patel
Nilang Patel

 

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Java 9 Dependency Injection

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 author(s), 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.

Commissioning Editor: Merint MathewAcquisition Editors: Denim Pinto / Nitin DasanContent Development Editor: Anugraha ArunagiriTechnical Editor: Jijo MaliyekalCopy Editor: Safis EditingProject Coordinator: Ulhas KambaliProofreader: Safis EditingIndexer: Rekha NairGraphics: Tania DuttaProduction Coordinator: Arvindkumar Gupta

First published: April 2018

Production reference: 1250418

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

ISBN 978-1-78829-625-0

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

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.

Contributors

About the authors

Krunal Patel has been working at Liferay Portal for over 5 years and has over 9 years of experience in enterprise application development using Java and Java EE technologies. He has worked in various domains, such as healthcare, hospitality, and enterprise intranet.

He was awarded an ITIL® Foundation Certificate in IT Service Management in 2015, a Liferay 6.1 Developer Certification in 2013, and a MongoDB for Java Developers certificate in 2013.

He has reviewed Mastering Apache Solr 7.x by Packt Publishing.

I would like to thank my loving wife Jigna, son Dirgh, father Maheshbhai, mother Sudhaben, brother Niraj, sister-in-law Krishna, and niece Risha, for supporting me throughout the course of writing this book. Thanks also to KNOWARTH, my coauthor and the Packt team, especially Anugraha and Peter Verhas, for their insightful comments.

 

 

 

Nilang Patel has over 14 years of core IT experience in leading project, software design and development, and supporting enterprise applications using enterprise Java technologies.

He is experienced in core Java/J2EE based application and has experience in healthcare, human resource, taxation, intranet application, energy and risk management domain. He contributes to various forums and has a personal blog.

He acquired the Liferay 6.1 Developer Certification in 2013, Brainbench Java 6 certification in 2012, and a Sun Certified Programmer for the Java 2 Platform 1.5 (SCJP) in 2007.

With the divine blessings of Bhagwan Swaminarayan and my guru HH Pramukh Swami Maharaj and Mahant Swami Maharaj, I, Nilang could accomplish such a wonderful milestone. I am equally thankful to all reviewers at Packt. I would like to express my deep gratitude to my wife Komal and my daughters Bhakti and Harmi for making all possible adjustments and for their support.

About the reviewer

Peter Verhas is a senior software engineer and software architect with a background in electrical engineering and economics. He gained an MSc from TU Budapest and an MBA from PTE Hungary, and studied at TU Delft and TU Vienna too. He created his first programs in 1979, and since then, he has authored several open source programs.

Peter now works for EPAM Systems in Switzerland, participating in software development projects at various customer sites. He also supports talent acquisition, interviewing candidates, and designing internal mentoring and training programs for developers.

 

 

 

 

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 and Credits

Java 9 Dependency Injection

Packt Upsell

Why subscribe?

PacktPub.com

Contributors

About the authors

About the reviewer

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

Download the color images

Conventions used

Get in touch

Reviews

Why Dependency Injection?

Design patterns

Dependency Inversion Principle

Inversion of Control

Implementing DIP through IoC

Inverting the interface

Inverting object creation 

Different ways to invert object creation

Inversion of object creation through the factory pattern

Inversion of object creation through service locator

Dependency injection

Dependency injection types

Constructor injection

Setter injection

Interface injection

IoC containers

Summary

Dependency Injection in Java 9

Java 9 introduction

Key features

Java Platform Module System

JShell (REPL) – The Java Shell

JLink – Module Linker

Multi-release JAR files

Stream API enhancements

Stack-walking API

Immutable collections with convenient factory methods

HTTP/2.0 support

Modular Framework in Java 9

What is modularity?

Java Platform Module System

The need for a Java modular system

Modular JDK 

What is a module?

Structure of a module

Module Descriptor (module-info.java)

Module types

Dependency Injection using the Java 9 Modular Framework

Modules with Service Loader

Service (API) module

Service provider (Implementation) module

Service client application

Writing modular code using a command-line interface

Defining dependency between modules

Compiling and running modules

Summary

Dependency Injection with Spring

A brief introduction to Spring framework

Spring framework architecture

Core container layer

Data access/integration layer

Spring web layer

Spring test

Miscellaneous

Bean management in Spring container

Spring IoC container

Configuration

Containers in action

Dependency Injection (DI) in Spring

Constructor-based DI

Setter-based DI

Spring DI with the factory method

Static factory method 

Instance (non-static) factory method

Auto-wiring in Spring

Auto-wiring by name

Auto-wiring by type

Auto-wiring by constructor

Annotation-based DI

DI through XML configuration

Defining annotation

Activating annotation-based configuration

Defining a Java class as <bean> with annotation

Annotation with the factory method

DI with Java configuration

Summary

Dependency Injection with Google Guice

A brief introduction to the Google Guice framework

Guice setup

Dependency injection and JSR-330

Example of simple DI

Basic injection in Guice

Guice API and Phases

Start up phase

Module interface

The AbstractModule class

Binder

Injector

Guice

Provider

Runtime phase

Guice annotations

Inject

ProvidedBy

ImplementedBy

@Named

Binding in Guice

Linked bindings

Instance bindings

Untargeted bindings

Constructor bindings

Built-in bindings

Just-in-time Bindings

Binding annotations

Guice injection

Constructor Injection

Method injection

Field injection

Optional injection

Static injection

Summary

Scopes

Introduction to bean scopes in Spring

Bean definition 

Spring scopes

Singleton scope

Prototype scope

Request scope

Session scope

Application scope

Global session scope

websocket scope

How to define a bean scope

XML metadata configuration

Using the singleton scope

Using the prototype scope

Java configuration using annotations

Singleton scope with annotation

Prototype scope with annotation

Dependency injection and the bean scope

How to choose a bean scope

Scopes in Google Guice

Default scope

Singleton scope

Eager singletons

Summary

Aspect-Oriented Programming and Interceptors

AOP introduction

Spring AOP

XML(schema)-based Spring AOP

Declaring aspect

Declaring a point-cut

Point-cut designator

Patterns

Declaring Advice (interceptor)

Implementing before advice

Implementing after advice

Implementing around advice

Implementing after returning advice

Implementing AfterThrowing advice

@AspectJ annotation-based Spring AOP

Declaring aspect

Declaring point-cut

Declaring Advice

Declaring an advisor

Choosing AOP frameworks and style of configuration

Spring AOP versus AspectJ language

XML versus @AspectJ-style annotation for Spring AOP

Summary

IoC Patterns and Best Practices

Various patterns to achieve IoC

The factory method pattern

Defining the product (abstract type) and its concrete implementation

Defining the factory method (creator interface) and its concrete implementation

The service locator pattern

The template method pattern

The strategy pattern

Configuration styles

File-based (XML) versus code-based configuration

Injection using the setter method versus the constructor

Constructor-based DI

Setter-based DI

Circular dependency

Problems of circular dependency

Causes and solutions

The single responsibility principle

Deferring the setting of a dependency from constructor to setter

Relocation of classes and packages

Circular dependency in the Spring framework

Using setter/field injection over constructor injection

Using the @Lazy annotation

Best practices and anti-patterns

What to inject – the container itself or just dependencies?

Excessive injection

Achieving IoC in the absence of a container

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Dependency Injection is a design pattern that allows us to remove the hardcoded dependencies and make our application loosely coupled, extendable, and maintainable. We can implement dependency injection to move the dependency resolution from compile-time to runtime. This book will be your one-stop guide to writing loosely coupled code using the latest features of Java 9 with frameworks such as Spring 5 and Google Guice.

Who this book is for

This book is for Java developers who would like to understand how to implement Dependency Injection in their applications. Prior knowledge about the Spring and Guice frameworks and Java programming is assumed.

What this book covers

Chapter 1, Why Dependency Injection?, gives you a detailed insight into various concepts, such as Dependency Inversion of Principle (DIP), Inversion of Control (IoC), and Dependency Injection (DI). It also talks about practical use cases where DI is commonly used.

Chapter 2, Dependency Injection in Java 9, gets you acquainted with Java 9 features and its modular framework, and explains how to implement DI using the service loader concept.

Chapter 3, Dependency Injection with Spring, teaches you how to manage dependency injection in the Spring framework. It also describes a different way to implement DI using Spring.

Chapter 4, Dependency Injection with Google Guice, talks about Guice and its dependency mechanism, and it teaches us dependency binding and the various injection methods of the Guice framework.

Chapter 5, Scopes, teaches you about the different scopes defined in the Spring and Guice frameworks.

Chapter 6, Aspect-Oriented Programming and Interceptors, shows the purpose of Aspect-Oriented Programming (AOP), how it solves different design problems by isolating repeated code from applications and plug them dynamically using Spring framework.

Chapter 7, IoC Patterns and Best Practices, gives an overview of various design patterns that can use to achieve IoC. Apart from this, you will be acquainted with best practices and anti-patterns to follow while injecting DI.

To get the most out of this book

It would be good if you know Java, Spring, and the Guice

framework. This will help you understand dependency injection

We assume you have an installation of Java 9, and Maven on your system, before beginning

Download the example code files

You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit 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 at

www.packtpub.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 athttps://github.com/PacktPublishing/Java-9-Dependency-Injection. We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/Java9DependencyInjection_ColorImages.pdf.

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: "Mount the downloaded WebStorm-10*.dmg disk image file as another disk on your system."

A block of code is set as follows:

module javaIntroduction {}

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

$ mkdir css

$ cd css

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: "Select System info from the Administration panel."

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: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

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.packtpub.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 [email protected] 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 packtpub.com.

Why Dependency Injection?

In software development, very often someone else might already have found effective solutions to the problems you are facing.

As a developer, you don't need to reinvent the wheel every time. Instead, you need to refer to the well-established practices and methodologies. Have you guessed what we are talking about? That's correct: design patterns.

This chapter is crafted to cover the following interesting topics:

What design patterns are and their benefits

Dependency Injection Principle

(

DIP

)

Inversion of Control

(

IoC

)—a design methodology to implement DIP

Various design patterns to implement IoC

Dependency Injection

(

DI

)

Various types to implement DI

How an IoC container is helpful to apply a DI

Design patterns

By definition, a design pattern is a set of proven de facto industry standards and best practices for resolving recurring problems. Design patterns are not ready-made solutions. Rather, they're a way or template to implement and apply the best possible solution for your problem.

It's equally true that if a design pattern is not implemented in the right way, it creates a lot of problems rather than solving the one you expected to solve. So it's very important to know which design pattern, if any, is right for a specific scenario.

Design patterns are a common paradigm to describe the problem and how to solve it. It's usually not language specific. Design patterns can protect you from the design problems that generally occur in the later stages of development.

There are numerous advantages to using design patterns, as follows:

Improves software reusability

Development cycle becomes faster

Makes the code more readable and maintainable

Increases the efficiency and enhances the overall software development

Provides common vocabulary to describe problems and best possible solutions in a more abstract way

And you can count many more. In the following sections, we will gain a deep understanding of how to make your code modular, loosely coupled, independent, testable, and maintainable, by following certain principles and patterns.

This chapter will cover in-depth ideas about the Dependency Inversion Principle (DIP), the Inversion of Control paradigm, and DI design pattern.

Most developers use the terms design principle and design pattern interchangeably, even though there is a difference between them.

Design principle: Generically, this is a guideline about what is the right way and what is the wrong way to design your application. Design principles always talk about what to do instead of how to do it.

Design patterns: A generic and reusable solution for commonly occurring problems. Design patterns talk about how to solve the problems in a given software design context by providing clear methodologies.

The first step towards making your code cleaner, readable, decoupled, maintainable, and modular is to learn the design principle called DIP.

Inversion of Control

IoC is a design methodology used to build a loosely coupled system in software engineering by inverting the control of flow from your main program to some other entity or framework.

Here, the control refers to any additional activities a program is handling other than its main activities, such as creating and maintaining the dependency objects, managing the application flow, and so on.

Unlike procedural programming style, where a program handles multiple unrelated things all together, IoC defines a guideline where you need to break the main program in multiple independent programs (modules) based on responsibility and arrange them in such a way that they are loosely coupled.

In our example, we break the functionality into separate modules. The missing part was how to arrange them to make them decoupled, and we will learn how IoC makes that arrangement. By inverting (changing) the control, your application becomes decoupled, testable, extensible, and maintainable.

Implementing DIP through IoC

DIP suggests that high-level modules should not depend on low-level modules. Both should depend on abstraction. IoC provides a way to achieve the abstraction between high-level and low-level modules.

Let's see how we can apply DIP through IoC on our Balance Sheet example. The fundamental design problem is that high-level modules (balance sheet) tightly depend on low-level (fetch and export data) modules.

Our goal is to break this dependency. To achieve this, IoC suggests inverting the control. In IoC, inverting the control can be achieved in the following ways:

Inverting the interface

: Make sure the high-level module defines the interface, and low-level modules follow it

Inverting object creation

: Change the creation of dependency from your main modules to some other program or framework

Inverting flow

:

 

Change the flow of application