Video in progress
In Spring, do you need to write an interface for every service if it has only one implementation?
Not necessarily. Spring works with classes too, through CGLIB proxies, and Mockito can mock classes. An interface is useful at a real abstraction boundary, where you talk to another module or an external system; an XxxService + XxxServiceImpl pair for everything is often just noise.
📖 Answer
The historical reasons:
- old Spring used JDK dynamic proxies, which only worked with interfaces. Since Spring Boot 2 the default is CGLIB (
proxyTargetClass=true), and the class itself is proxied; - old mock libraries could only mock interfaces. Mockito solved this long ago (in Mockito 5, the default
inlinemock maker can mock evenfinalclasses).
The cost of a UserService / UserServiceImpl pair:
- every method changes in two places;
- "Go to implementation" in the IDE is an extra step;
- the name
Implsays nothing: it isn't an abstraction, it's a copy.
When an interface is right:
- a DIP boundary: the domain declares
PaymentGatewayand infrastructure implements it. The interface is what flips the direction of the dependency. - Several real implementations:
Notifierwith SMS, Telegram, email. - A module's public API: another team uses your module and you want to hide the internal classes.
- A fake for tests: when an in-memory
ClockorOrderStoreis more convenient than a mock.
If you need a second implementation later, the IDE's "Extract Interface" refactoring takes 10 seconds. YAGNI works correctly here.
One more thing: a CGLIB proxy doesn't work with final classes and final methods, and it may call the constructor twice (Objenesis largely solves this problem).
Sign up to mark studied questions and save your progress.