3 The Spring context: Wiring beans
This chapter covers
- Establishing relationships among beans
- Using dependency injection
- Accessing the beans from the Spring context through dependency injection
We’ve discussed the Spring context: the part of the application where Spring manages the objects it needs to control. These managed objects, called beans, are added to the context so Spring can enhance them with features such as dependency injection, transactions, or security. You also learned the main ways to define beans and register them in the Spring context.
Now we’ll focus on how beans work together. In real applications, objects rarely work alone. They collaborate and delegate responsibilities to one another. Instead of manually retrieving beans with getBean(), we usually let Spring automatically provide the needed references between beans. This is how we establish relationships among the objects managed by the framework.
There are two main ways to establish relationships among beans. The first is to link beans directly by calling the methods that created them, which we call the wiring. The second is to get Spring to provide us a value using a method parameter, which we call autowiring.
We’ll explore both methods in this lesson through a combination of examples, diagrams, and code snippets. Understanding the relationships between beans is fundamental to using Spring effectively, and almost every Spring application relies on the concepts we’ll discuss here now.