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

In this chapter, we discuss using abstraction with Spring beans. This topic is essential because in real-world projects, we often use abstractions to decouple implementations. As you’ll learn in this chapter, we ensure our application is comfortable to maintain and test by decoupling implementations.

We’ll start with a refresher on how to use interfaces to define contracts in section 4.1. To approach this subject, we begin by discussing objects’ responsibilities and find out how they fit in a standard class design of an app. We’ll use our coding skills to implement a small scenario in which we don’t use Spring, but we focus on implementing a requirement and using abstractions to decouple the app’s dependent objects.

We then discuss Spring’s behavior when using DI with abstractions in section 4.2. We’ll start from the implementation we worked on in section 4.1 and add Spring to the app’s dependencies. We then use the Spring context to implement dependency injection. With this example, we get closer to what you expect to find in production-ready implementations: objects with typical responsibilities for real-world scenarios and abstraction used with DI and the Spring context.

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

Summary