Hi there Spring/SpringBoot fans/experts,
Hope you’re doing well. I’ve been grappling with this question for a while now, and I thought I’d ask a spring/springboot expert for their opinion and experience on it. It’s about interface as it relates to its usage in springboot.
First of all let me say this; from a Java or software engineering stand point, I understand and am well aware of the use or purpose of interfaces, they are contracts.
So, from springboot as a FRAMEWORK/library standpoint, it make sense in the framework source code.
Now, from springboot as an APPLICATION I’ve seen cases where every service class (@Service) has a corresponding interface :
public interface MyService {}
public class MyServiceImpl implement MyService {}
99.99% of the time, these interfaces never get implemented by anything else ever. Why has this become such a popular thing to do in springboot, where every single service class has a corresponding interface even though nothing else will ever implement these interfaces?
To me it seems to create more complexity and code to maintain with no apparent benefits. Note that I’m strictly referring to @Service
class interfaces only.
Is it good practice to do that? Is there something I’m missing here. What’s your experience and thoughts on this please?
Thank you in advance!
CodePudding user response:
This pattern was indeed used quite a bit in quite some tutorials and online resources but I'd argue it's quite outdated. Back in the XML days, you didn't have such a thing as a configuration class so the main way of configuring a bean was an XML entry, with public setters for the collaborators. As you didn't want to expose that in your API, having an interface that declares your public API and the implementation taking care of it made sense.
With modern Spring, this view of the world is totally outdated and there's certainly not a strong desire on our side for such a paradigm. Constructor injection is the norm now, and with that, the separation between an interface and its sole implementation is not very useful.
One could argue that they don't want any Spring annotations to surface on public APIs so this as still a use. That said, if you use construction injection and explicit bean registration, you don't need any annotations for dependency injection. If you're feeling strongly about this and use additional aspects such as transaction or caching, then yes you'll have to create an interface if you want to hide those annotations from your public API.
CodePudding user response:
In spring, @Service is usually responsible for specific business logic, and business code usually contains a lot of changes. So it is generally implemented using interfaces. I don't quite understand why your business code is always empty.