Book Image

Java 9 Dependency Injection

By : Nilang Patel, Krunal Patel
Book Image

Java 9 Dependency Injection

By: Nilang Patel, Krunal Patel

Overview of this book

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.
Table of Contents (14 chapters)
Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
Index

Scopes in Google Guice


Most of the scopes we have seen for the Spring Framework similarly exist in Google Guice. Scope defines that code should work in a specific context, and in Guice, the Injector manages the scope context. Default scope (No Scope), singleton, session, and request are the main scopes in Guice.

Default scope

By default, Guice injects a new and separate instance of an object for each dependency (similar to the prototype scope in Spring), whereas Spring provides singletons by default. 

Let us consider an example of a house that has a family with three people, all with their own personal car. Every time they call the injector.getInstance() method, a new instance of a car object is available for each family member:

home.give("Krunal", injector.getInstance(Car.class));

home.give("Jigna", injector.getInstance(Car.class));

home.give("Dirgh", injector.getInstance(Car.class));

Singleton scope

If we want to create only one instance of the class, then the @Singleton annotation can be...