Why the need for a strict enforcement of interfaces for classes in a Spring MVC service layer?
In the Spring web app I am working on, there is a service layer that relates to the rest of the web app structure like this:
com/
myapp/
controller/
model/
service/
This service layer is made up of interface and impl开发者_如何学Cementation classes.
Why is it so important to have interfaces for all of these classes?
Why not just Class files?
The Interfaces allow you to pass different implementations of those interfaces without changing the underlying code.
For example, if a model only wanted HashMap and you had a TreeMap, you'd be in trouble. But if the model accepted Map (ok, pretend it's an Interface) then it would work with either HashMap or TreeMap.
I believe Spring will create a proxy class in many instances. The proxy class implements your interface, and eventually delegates to your implementation, but may do some stuff in between like transaction management. If you use an interface then your code doesn't care whether it gets your implementation directly, or a spring proxy implementation.
精彩评论