There are 3 main reasons: IMO:
First reason: proxy.
If you ask Spring for a bean of type UserDAO, it will actually return a proxy encapsulating the actual instance of UserDAOImpl. This allows him to distinguish between transactions, check security authorization, access to logs, calculation statistics, etc. This can be done without an interface, but then bytecode processing is required.
The second reason: verifiability.
When unit testing a business service using UserDAO, you typically introduce a mock implementation of UserDAO. Once again, this is easier to do when UserDAO is an interface. It is possible with a specific class, but it has not always been, and even easier with the interface
Third reason: denouement.
Using the interface, you have a place where you define a real DAO contract for your customers. Of course, a specific implementation needs the setDataSource() method, but that doesn’t setDataSource() clients. All they need is a set of data access methods offered by the DAO. By separating the interface and the specific implementation, you will see that the client does not rely on the details of the DAO implementation.
JB Nizet Jan 17 2018-12-17T00: 00Z
source share