spring and interfaces

后端 未结 9 790
无人及你
无人及你 2020-12-08 14:45

I read all over the place about how Spring encourages you to use interfaces in your code. I don\'t see it. There is no notion of interface in your spring xml configuration.

9条回答
  •  时光取名叫无心
    2020-12-08 15:13

    Spring won't force you to use interfaces anywhere, it's just good practice. If you have a bean that has a some properties that are interfaces instead of concrete classes, then you can simply switch out some objects with mockups that implement the same interface, which is useful for certain test cases.

    If you use for example the Hibernate support clases, you can define an interface for your DAO, then implement it separately; the advantage of having the interface is that you will be able to configure it using the Spring interceptors, which will allow you to simplify your code; you won't have to write any code cathing HibernateExceptions and closing the session in a finally segment, and you won't have to define any transactions programmatically either, you just configure all that stuff declaratively with Spring.

    When you're writing quick and dirty apps, you can implement some simple DAO using JDBC or some simple framework which you won't end up using in the final version; you will be able to easily switch those components out if they implement some common interfaces.

提交回复
热议问题