Java 9 Dependency Injection
eBook - ePub

Java 9 Dependency Injection

Nilang Patel, Krunal Patel

Buch teilen
  1. 246 Seiten
  2. English
  3. ePUB (handyfreundlich)
  4. Über iOS und Android verfügbar
eBook - ePub

Java 9 Dependency Injection

Nilang Patel, Krunal Patel

Angaben zum Buch
Buchvorschau
Inhaltsverzeichnis
Quellenangaben

Über dieses Buch

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.

Häufig gestellte Fragen

Wie kann ich mein Abo kündigen?
Gehe einfach zum Kontobereich in den Einstellungen und klicke auf „Abo kündigen“ – ganz einfach. Nachdem du gekündigt hast, bleibt deine Mitgliedschaft für den verbleibenden Abozeitraum, den du bereits bezahlt hast, aktiv. Mehr Informationen hier.
(Wie) Kann ich Bücher herunterladen?
Derzeit stehen all unsere auf Mobilgeräte reagierenden ePub-Bücher zum Download über die App zur Verfügung. Die meisten unserer PDFs stehen ebenfalls zum Download bereit; wir arbeiten daran, auch die übrigen PDFs zum Download anzubieten, bei denen dies aktuell noch nicht möglich ist. Weitere Informationen hier.
Welcher Unterschied besteht bei den Preisen zwischen den Aboplänen?
Mit beiden Aboplänen erhältst du vollen Zugang zur Bibliothek und allen Funktionen von Perlego. Die einzigen Unterschiede bestehen im Preis und dem Abozeitraum: Mit dem Jahresabo sparst du auf 12 Monate gerechnet im Vergleich zum Monatsabo rund 30 %.
Was ist Perlego?
Wir sind ein Online-Abodienst für Lehrbücher, bei dem du für weniger als den Preis eines einzelnen Buches pro Monat Zugang zu einer ganzen Online-Bibliothek erhältst. Mit über 1 Million Büchern zu über 1.000 verschiedenen Themen haben wir bestimmt alles, was du brauchst! Weitere Informationen hier.
Unterstützt Perlego Text-zu-Sprache?
Achte auf das Symbol zum Vorlesen in deinem nächsten Buch, um zu sehen, ob du es dir auch anhören kannst. Bei diesem Tool wird dir Text laut vorgelesen, wobei der Text beim Vorlesen auch grafisch hervorgehoben wird. Du kannst das Vorlesen jederzeit anhalten, beschleunigen und verlangsamen. Weitere Informationen hier.
Ist Java 9 Dependency Injection als Online-PDF/ePub verfügbar?
Ja, du hast Zugang zu Java 9 Dependency Injection von Nilang Patel, Krunal Patel im PDF- und/oder ePub-Format sowie zu anderen beliebten Büchern aus Informatik & Programmierung in Java. Aus unserem Katalog stehen dir über 1 Million Bücher zur Verfügung.

Information

Jahr
2018
ISBN
9781788296472

Dependency Injection with Spring

So far, we have learned why modularity is so important in writing cleaner and maintainable code. In Chapter 1, Why Dependency Injection?, we learned about the Dependency Inversion Principle (DIP), IoC (a design methodology to implement DIP), and various design patterns to implement IoC. Dependency Injection (DI) is one of the design patterns to achieve IoC.
In the Chapter 2, Dependency Injection in Java 9, we learned how modular framework and DI are facilitated in Java 9. In this chapter, we will continue our journey to learn DI in Spring—one of the most popular and widely used frameworks to implement enterprise applications.
In this chapter, we will explore the following topics:
  • A brief introduction to Spring framework
  • Bean management in Spring
  • How to achieve DI with Spring
  • Auto wiring: he feature of resolving dependency automatically
  • Annotation-based DI implementation
  • DI implementation with Java-based configuration

A brief introduction to Spring framework

Spring is a lightweight and open source enterprise framework created way back in 2003. Modularity is the heart of Spring framework. Because of this, Spring can be used from the presentation layer to the persistence layer.
The good thing is, Spring doesn't force you to use Spring in all layers. For example, if you use Spring in the persistence layer, you are free to use any other framework in presentation of the controller layer.
Another good part of Spring is its Plain Old Java Object (POJO) model-based framework. Unlike other frameworks, Spring doesn't force your class to extend or implement any base class or interface of Spring API; however, Spring does provide a set of classes to use other frameworks, such as ORM frameworks, logging framework, Quartz timers, and other third-party libraries, which will help you to integrate those frameworks with Spring.
More on this: Spring allows you to change the similar framework without changing the code. For example, you can choose different persistence frameworks just by changing the configuration. This is also applicable to third-party API integration with Spring.
Spring is a POJO-based framework; a servlet container is suffice to run your application and a fully-fledged application server is not required.

Spring framework architecture

Spring is a modular framework. This brings great flexibility to choosing the modules that you need instead of bringing all of them together in your code. Spring comprises around 20 modules that are logically grouped into the following layers:
  • Core container layer
  • Data access/integration layer
  • Web layer
  • Test layer
  • Miscellaneous layer

Core container layer

Being a main part of the framework, the core container covers the following modules:
Spring core: As its name suggests, it provides core functionalities of the framework, including an IoC container and DI mechanism. An IoC container isolates the configuration and dependencies management from the application code.
Spring beans: This module provides the bean factory to create and manage the life cycle of beans (objects). It is a factory pattern implementation.
Spring context: This module is built on top of core and bean modules. Its entry point is to load the configuration and access the objects. On top of bean modules, the context module provides some additional features such as event propagation, creating context on the fly, internationalization, and so on.
Spring Expression Language (SpEL): This is an expression language to access and manipulate objects on the fly in JSP. It's an extension of Expression Language (EL) of JSP 2.1 specification. Using SpEL makes the JSP code cleaner, more readable, and maintainable. Major benefits of using SpEL are:
  • The setting of and getting properties' values of objects with ease
  • It can directly invoke controller methods to get the data
  • It's used to retrieve objects directly from Spring's application context (IoC container)
  • It supports various list operations such as projection, selection, iteration, and aggregation
  • It provides logical and arithmetic operations

Data access/integration layer

Spring data access and the integration layer is used for data manipulation and other integration. It covers the following modules:
  • Transaction: This module helps maintain transactions in a programmatic and declarative manner. This module supports ORM and JDBC modules.
  • Object XML mapping (OXM): This module provides abstraction of Object/XML processing, which can be used by various OXM implementation such as JAXB, XMLBeans, and so on, to integrate with Spring.
  • Object Relationship Mapping (ORM): Spring doesn't provide its own ORM framework; instead it facilitates integration with ORM frameworks such as Hibernate, JPA, JDO, and so on, with this module.
  • Java Database Connectivity (JDBC): This module provides all low-level boilerplate code to deal with JDBC. You can use it to interact with databases with standard JDBC API.
  • Java Messaging Service (JMS): This module supports integration of messaging systems in Spring.

Spring web layer

Spring web layer is used to create web-based applications. It is comprised of the following modules:
  • Web: This module provides basic web-related features such as multipart file upload (with the help of Spring custom tags in JSP). It is also responsible for initialization of IoC containers in web context.
  • Servlet: This module provides implementation of Spring MVC (Model View Controller) for web-based applications. It provides clear separation of views (presentation layer) from models (business logic), and controls the flow between them with controllers.
  • Portlet: This module provides MVC implementation for a portlet, and it is mainly used in portal environments.

Spring test

This provides support for unit and integration testing with various unit-testing frameworks, such as JUnit and TestNg. We will see how to perform unit testing with Spring in upcoming sections in this chapter, so keep reading.

Miscellaneous

Some additional modules are also part of the Spring framework:
  • Aspect and AOP: These modules provide a facility to apply common logic (called concerns in AOP terminology) across multiple application layers dynamically
  • Instrumentation: This module provides a class instrumentation facility and class loader implementation
  • Messaging: This module provides support for Streaming Text-Oriented Messaging Protocol (STOMP) for communicating with various STOMP-based clients

Bean management in Spring container

When any software application is being executed, a set of objects are created and interact with each other to achieve specific business goals. Being a POJO-based programming model, the Spring framework treats all the objects of classes in your application as POJO or beans (in a Spring-friendly way).
These objects or beans should be independent in a manner that they can be re-used or changed without causing the ripple effect of changing others. Being loosely coupled this way, it also provides the benefit of doing testing without much worry of any dependency.
Spring provides an IoC container, which is used to automate the process of supplying external dependency to your class. You need to give instruction (in the form of configuration) about your client and dependencies. Spring will manage and resolve all your dependencies at runtime. Moreover, Spring provides a facility to keep availability of your dependencies at various application scopes, such as request, session, application, and so on.
It's essential to understand how Spring manages the life cycle (the process of creating, managing, and destroying) of objects before getting an idea about injecting dependency. In Spring, all these responsibilities are performed by the Spring IoC container.

Spring IoC container

In Spring, the org.springframework.beans.factory.BeanFactory interface defines the basic IoC container, while the org.springframework.context.ApplicationContext interface represents an advanced IoC container. ApplicationContext is a super set of BeanFactory. It provides some additional enterprise-level functionalities on top of basic IoC features by BeanFactory.
To cater for different types of applications, Spring provides various implementations of ApplicationContext out of the box. For standalone applications, you can use the FileSystemXmlApplicationContext or ClassPathXmlApplicationContext class. They are both implementations of ApplicationConext.
While working with Spring, you need to pass one XML file as an entry point for these containers. This file is called the Spring Application Context file. When the Spring container starts, it loads this XML file and starts configuring your beans (either with XML-based bean definition in this file, or annotation-based definition in your POJO Java class).
  • FileSystemXmlApplicationContext: This conta...

Inhaltsverzeichnis