Chapter 4: The Spring context: Using abstractions
This introduction explains why Spring applications use interfaces to decouple components and dependency injection to supply implementations.
After this chapter you will be able to
- Interface-based decoupling. Explain how an interface separates what a component needs from how that behavior is implemented, and why depending directly on a concrete implementation makes code harder to change, extend, and test.
- Spring injection through abstractions. Describe Spring's role in supplying an implementation through its context at runtime when components use abstractions.
- Interface responsibility and implementations. Explain that a Java interface declares a responsibility that implementing objects must define, and that different classes can fulfill it in different ways.
- Sorter interface decoupling. Describe how making DeliveryDetailsPrinter depend on Sorter rather than SorterByAddress allows different sorting implementations without further changes to the printer.
- Comment publication requirements. Describe what the task-management app must do when a user publishes a comment on a task.
- Publish Comment Responsibilities. Describe how the publish-comment use case is divided among a service, a repository, and a notification proxy.
- Interface Based Service Dependencies. Explain why CommentService depends on repository and notification interfaces, and describe what an implementation supplies to a contract.
- Abstraction based dependencies in projects. Explain why dependency injection with abstractions is an important topic in Spring applications.
- Spring context membership. Explain how to decide whether an object belongs in the Spring context, and apply the decision to the Comment example.
- Concrete component selection. Describe which classes receive @Component and why the interfaces do not, including how Spring finds the annotated classes.
- Interface typed dependency wiring. Trace how Spring supplies CommentService with its dependencies declared as interfaces, and explain the benefit shown by the example.
- Ambiguous interface injection. Explain why injecting a CommentNotificationProxy fails when the Spring context contains two beans implementing that interface and neither has been selected.
- Default implementation with @Primary. Describe how @Primary makes one implementation the default for injection and why that is useful when a dependency supplies an unsuitable implementation.
- Named selection with @Qualifier. Explain how @Qualifier selects a named implementation for injection when different objects need different implementations of the same interface.
- Service and repository responsibilities. Distinguish a service, which implements use cases, from a repository, which manages data persistence, and explain why marking those roles helps developers read the class design.
What it builds on
- Using the @Autowired annotation to inject beans (chapter 3) · Introduces using Spring to inject beans.
- Using stereotype annotations to create beans (chapter 2) · Creating beans with stereotype annotations.
- Choosing from multiple beans in the Spring context (chapter 3) · Choosing from multiple beans in the Spring context
Section by section
Introduction
This introduction explains why Spring applications use interfaces to decouple components and dependency injection to supply implementations.
- Interface-based decoupling: Explain how an interface separates what a component needs from how that behavior is implemented, and why depending directly on a concrete implementation makes code harder to change, extend, and test.
Why it matters: Depending on a contract rather than a particular class makes application components easier to maintain. - Spring injection through abstractions: Describe Spring's role in supplying an implementation through its context at runtime when components use abstractions.
Why it matters: Dependency injection lets components work with abstractions while Spring supplies the implementation they use.
Key terms: abstractions, interfaces, concrete implementations, dependency injection, Spring context, implementation
4.1 Using interfaces to define contracts
This section explains how Java interfaces state a responsibility without prescribing its implementation, so objects can express what they need rather than demand a particular solution.
- Interface responsibility and implementations: Explain that a Java interface declares a responsibility that implementing objects must define, and that different classes can fulfill it in different ways.
Why it matters: This distinction lets you describe a required behavior without tying it to one implementation. - Needs rather than specific solutions: Explain why an object should express the responsibility it needs through an interface rather than insist on a particular solution, using the radio example if helpful.
Why it matters: Expressing the need avoids committing to a solution that may not be the best fit.
Key terms: interface, responsibility, implementation, interfaces, what you need, solution
4.1.1 Using interfaces for decoupling implementations
The section shows how depending on a Java interface instead of a concrete class lets a printing object use different sorting implementations without changing the printer.
- Concrete sorting dependency costs: Explain why directly depending on SorterByAddress makes DeliveryDetailsPrinter harder to change when delivery details need a different sort order.
Why it matters: This is the change that the interface-based design aims to avoid. - Sorter interface decoupling: Describe how making DeliveryDetailsPrinter depend on Sorter rather than SorterByAddress allows different sorting implementations without further changes to the printer.
Why it matters: Depending on the interface keeps a change in sorting behavior from spreading into the printer.
Key terms: DeliveryDetailsPrinter, SorterByAddress, concrete implementation, Sorter interface, decouple, implementation
4.1.2 The requirement of the scenario
Introduces a task-management comment feature whose publication triggers storage and an email notification.
- Comment publication requirements: Describe what the task-management app must do when a user publishes a comment on a task.
Why it matters: These requirements define the feature that the following implementation must support.
Key terms: task, comment, configured address
4.1.3 Implementing the requirement without using a framework
This section builds a framework-free publish-comment example by separating responsibilities and making the service depend on interfaces rather than concrete implementations.
- Publish Comment Responsibilities: Describe how the publish-comment use case is divided among a service, a repository, and a notification proxy.
Why it matters: Separating these jobs makes each object's purpose clear. - Interface Based Service Dependencies: Explain why CommentService depends on repository and notification interfaces, and describe what an implementation supplies to a contract.
Why it matters: The service can keep using the same contracts if storage technology or notification channel changes. - Framework Free Example Components: Describe how the plain Maven example represents a comment and demonstrates its repository and proxy responsibilities without implementing real database access.
Why it matters: It distinguishes the example's working class design from real persistence or email infrastructure.
Key terms: use case, service, repository, proxy, CommentService, CommentRepository, interface, contract, abstractions, decouple
4.2 Using dependency injection with abstractions
Introduces Spring dependency injection with abstractions and explains why the topic matters, without yet teaching how to implement it.
- Abstraction based dependencies in projects: Explain why dependency injection with abstractions is an important topic in Spring applications.
Why it matters: It connects the upcoming Spring example to a common way applications express dependencies.
Key terms: dependencies between objects, abstractions, dependency injection
4.2.1 Deciding which objects should be part of the Spring context
The section shows how to choose which objects Spring should manage and wire a comment-publishing service through interface-typed dependencies.
- Spring context membership: Explain how to decide whether an object belongs in the Spring context, and apply the decision to the Comment example.
Why it matters: Putting only useful objects under Spring’s management avoids needless complexity. - Concrete component selection: Describe which classes receive @Component and why the interfaces do not, including how Spring finds the annotated classes.
Why it matters: Spring needs discoverable, instantiable classes to create the beans used in this example. - Interface typed dependency wiring: Trace how Spring supplies CommentService with its dependencies declared as interfaces, and explain the benefit shown by the example.
Why it matters: Interface-typed dependencies let Spring connect the service to its implementations without manual construction and wiring. - Alternative injection forms: Describe the injection forms the section says work with abstractions and distinguish the demonstrated field-injection change from the recommended approach.
Why it matters: Using interfaces does not limit dependency injection to one style, though the author favors constructor injection.
Key terms: Spring context, DI, Comment, @Component, @ComponentScan, stereotype annotations, CommentService, DBCommentRepository, EmailCommentNotificationProxy, CommentRepository
4.2.2 Choosing what to auto-wire from multiple implementations of an abstraction
This section explains how to resolve dependency injection when multiple Spring beans implement the same interface, using @Primary for a default or @Qualifier for a specific choice.
- Ambiguous interface injection: Explain why injecting a CommentNotificationProxy fails when the Spring context contains two beans implementing that interface and neither has been selected.
Why it matters: Recognizing the ambiguity tells you why an injection fails before you choose a remedy. - Default implementation with @Primary: Describe how @Primary makes one implementation the default for injection and why that is useful when a dependency supplies an unsuitable implementation.
Why it matters: A default resolves ambiguity when one implementation is generally the right choice for the app. - Named selection with @Qualifier: Explain how @Qualifier selects a named implementation for injection when different objects need different implementations of the same interface.
Why it matters: Naming the choice lets different objects receive the implementation each needs.
Key terms: Spring context, CommentNotificationProxy, NoUniqueBeanDefinitionException, @Primary, @Component, default, @Qualifier, CommentService, email, push notification
4.3 Focusing on object responsibilities with stereotype annotations
This section shows how @Service and @Repository make a Spring component’s responsibility explicit while still registering it in the context.
- Service and repository responsibilities: Distinguish a service, which implements use cases, from a repository, which manages data persistence, and explain why marking those roles helps developers read the class design.
Why it matters: The annotation lets someone reading a class see its intended role in the app. - Shared stereotype registration: Explain that @Component, @Service, and @Repository are all stereotype annotations that tell Spring to create an instance of the annotated class and add it to the context.
Why it matters: It explains why a class can have a more descriptive annotation and still become a Spring component.
Key terms: @Component, @Service, @Repository, service, repository, stereotype annotations, Spring context
4.4 Questions
This section provides self-check questions on interfaces, dependency injection, Spring-managed objects, and stereotype annotations, with answers in Appendix A.
4.5 Summary
Summarizes how interfaces decouple classes and how Spring injects and identifies implementations of those interfaces.
Where this is used later
- What Spring Data is (chapter 14) · The idea of using interfaces as abstractions.
- Calling REST endpoints using Spring Cloud OpenFeign (chapter 11) · Injecting Spring beans through abstractions
- Singleton beans in real-world scenarios (chapter 5) · Deciding which objects belong in the Spring context.
Concepts explained in this chapter
- interfaceA Java interface is a reference type that declares a responsibility or contract whose behavior must be provided by implementing classes.
- abstractionAn abstraction is a representation that separates the behavior an object requires from the details of how that behavior is implemented.
- stereotype annotationA stereotype annotation is a Spring annotation that declares an application class's role so Spring can detect and manage it as a component.
- repository patternA repository is an abstraction that provides access to stored application data.
- serviceA service is an application component responsible for implementing one or more use cases.
- component annotationThe component annotation is a Spring annotation that marks a class for automatic detection and registration as a bean.
- constructor injectionConstructor injection is a dependency-injection technique that supplies an object's dependencies through its constructor parameters.
- plain old java objectA Java object that does not require framework-specific inheritance or interfaces.
- MVC modelA model is an application object that represents data used by the application and made available for presentation.
- proxyA proxy object intercepts calls to a target object and can apply additional behavior before delegating to it.
- primary annotationThe @Primary annotation marks a Spring bean as the preferred candidate when multiple beans match a dependency.
- qualifier annotationThe @Qualifier annotation identifies which bean should be selected when multiple beans match an injection point.
- loose couplingDecoupling is the reduction of direct dependencies between software components so that one component's implementation can change independently of another's.
- @ServiceThe Spring @Service stereotype annotation marks a class as a service component eligible for detection and registration as a bean.
- repository annotationThe Spring @Repository stereotype annotation marks a class as a data-access component eligible for bean registration.
- dependency injectionDependency injection is a pattern in which an object's dependencies are supplied by an external component rather than constructed by the object itself.
- Spring beanAn object instance created, configured, and managed by the Spring IoC container.
- @BeanA Spring annotation that marks a method whose returned object is registered as a bean.
- @ComponentScan annotationA Spring annotation that configures package scanning for classes marked with component stereotype annotations.
- autowiringAutowiring is the technique of having Spring automatically resolve and establish dependencies among managed beans.
- field injectionField injection is a dependency-injection technique that assigns a dependency directly to an object's field.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
