chapter four

4 The Spring context: Using abstractions

 

This chapter covers

  • Using interfaces to define contracts
  • Using abstractions for beans in the Spring context
  • Using dependency injection with abstractions

It’s time to discuss how Spring beans work with abstractions. In real-world projects, we use abstractions to decouple implementations, which makes the application easier to maintain.

In a real application, objects rarely work alone. A controller may depend on a service, a service may depend on a repository, and each component needs other components to complete its work. If these dependencies point directly to concrete implementations, the code becomes harder to change, extend, and test.

Abstractions solve this problem by separating what an object needs from how that behavior is implemented. In Java, we usually define these abstractions with interfaces.

Spring uses dependency injection to provide the right implementation at runtime through its context. This combination—interfaces, clear responsibilities, and DI—is one of the most common ways to build maintainable Spring applications.

4.1 Using interfaces to define contracts

4.1.1 Using interfaces for decoupling implementations

4.1.2 The requirement of the scenario

4.1.3 Implementing the requirement without using a framework

4.2 Using dependency injection with abstractions

4.2.1 Deciding which objects should be part of the Spring context

4.2.2 Choosing what to auto-wire from multiple implementations of an abstraction

4.3 Focusing on object responsibilities with stereotype annotations

4.4 Questions

4.5 Summary