简体   繁体   中英

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 implementation 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM