What are the reasons for using interfaces (Java EE or Spring and JPA)

Most of the 2 classes (spring and JPA) are designed with interfaces. other than inheritance, are there any technical reasons? as a dynaimc or aop proxy, I need additional technical details about this

ex

public interface UserDAO { void delete(); void update(); void save(); List<User> get(); } public class UserDAOImpl implements UserDAO { public void delete(){} public void update(){} public void save(){} public List<User> get(){} } 
+3
spring java-ee design-patterns
Jan 17 2018-12-12T00:
source share
3 answers

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.

+21
Jan 17 2018-12-17T00:
source share
  • Interfaces for one are contracts, as I see them. For example, a set of software engineers (implementation classes) may have a specific contract with a company (Interface). A company may occasionally switch between engineers based on project needs. Since they fall under the same contract and follow the same rules, a transition is easier than bringing a resource from the outside (writing a new class) every time a project needs to be changed. You just need to change the configurations to switch implementation classes.

  • Interfaces are clean and provide one-point access to the rules that classes implement.

References

+6
Jan 17 2018-12-12T00:
source share

Because you mentioned Spring explicite.

Spring AOP can be used in various configurations. By default, java dynamic proxies ( java.lang.reflect.Proxy ) are used. This can only be applied to interfaces.

Spring AOP by default uses standard J2SE dynamic proxies for AOP proxies. This allows you to proxy any interface (or set of interfaces).

@see Spring Link Chapter 7.1.3 AOP Proxies @see Dynamic Proxy Classes

+5
Jan 17 '12 at 3:11
source share



All Articles