Chapter 1. Basics
Introduction
The Spring Framework has found a very strong user base over the years. Software houses and enterprises found the framework to be the best fit for their plumbing needs. Surprisingly, the core principle that Spring has been built for—the Dependency Injection (DI)—is very simple and straightforward to understand. In this chapter, we aim to discusses the fundamentals of the framework from a high ground. We will try to get a basic understanding of Dependency Injection principles. I will present a simple problem of object coupling and tight dependencies to begin with. Then we will aim to solve decoupling and dependencies by using Spring Framework.
Object Coupling Problem
Let us consider a simple program whose aim is to read data from various data sources. It should read data from a file system or database or even from an FTP server.
For simplicity, we will start writing a program that reads the data from a file system. The following example code is written without employing any best practices or dependency injection patterns—it’s just a simple and plain Java program that works.
This snippet shows a VanillaDataReaderClient class that uses
FileReader to fetch the data.
Example 1-1.
publicclassVanillaDataReaderClient{privateFileReaderfileReader=null;privateStringfileName="src/main/resources/basics/basics-trades-data.txt";publicVanillaDataReaderClient(){try{fileReader=newFileReader(fileName);}catch(FileNotFoundExceptione){System.out.println ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access