35,99 €
Create clean code with Dependency Injection principles
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.
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:
Seitenzahl: 254
Veröffentlichungsjahr: 2018
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 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.
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
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.
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.
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.
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.
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
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.
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.
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.
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
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!
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.
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."
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.
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.
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
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.
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.
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.
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
