When an object depends directly on another object’s implementation, changing that dependency can force changes in the object using it. An abstraction separates the behavior an object needs from the details of how that behavior is implemented. In Java, an interface commonly defines this contract: the interface says what can be done, and an implementing class defines how. section 4.0 section 4.4
Publishing a comment
CommentService publishes a comment by asking a CommentRepository to store it and a CommentNotificationProxy to send a notification. Both dependencies are interfaces. DBCommentRepository and EmailCommentNotificationProxy implement those contracts, so the service need not depend on their concrete classes. A different storage technology or notification channel can be introduced without changing the service’s dependency types. section 4.1.3
Listing 4.6 Implementing the CommentService object
public class CommentService {
private final CommentRepository commentRepository; #A
private final CommentNotificationProxy commentNotificationProxy; #A
public CommentService( #B
CommentRepository commentRepository,
CommentNotificationProxy commentNotificationProxy) {
this.commentRepository = commentRepository;
this.commentNotificationProxy = commentNotificationProxy;
}
public void publishComment(Comment comment) { #C
commentRepository.storeComment(comment);
commentNotificationProxy.sendComment(comment);
}
}The constructor accepts the two interfaces; publishComment calls their methods without choosing their implementations. section 4.1.3
An implementation still has to be supplied. In plain Java, code can construct the concrete dependencies and pass them to the service. With Spring, dependency injection can supply implementations from the Spring context instead. section 4.1.3 section 4.2
If multiple Spring beans match an interface, Spring needs guidance about which one to inject. Otherwise, the example with email and push notification beans raises a NoUniqueBeanDefinitionException. section 4.2.2
Two ways to resolve the choice are:
- Mark one implementation with @Primary to make it the default. section 4.2.2
- Use @Qualifier to identify a bean and request it at the injection point. This allows different objects to request different implementations. section 4.2.2
Abstractions also help unify a larger set of technologies. Spring Data provides common interfaces for persistence operations across different persistence technologies and supplies implementations, allowing applications to use a similar approach with less code. section 14.1























