public interface MyService {
void doSomething();
}
@Service
public class MyServiceImpl implements MyService {
@Override
public void doSomething() {
System.out.println("hello Im Impl Service");
}
}
다형성과 느슨한 결합
interface
를 사용함으로써, service
에 의존하는 class는 더 이상 service
의 구현에 의존하지 않게 된다. 이것이 service
를 독립적으로 사용할 수 있게 해준다.
느슨한 결합이 유용한 부분은 여러 가지 구현체를 가질 때이다.
AOP Proxy 사용
예전에는 Spring 에서 AOP Proxy 를 만드는 방식이 JDK Dynamic Proxy 를 사용하여 인터페이스 기반으로만 만들게 되어 있었다.
예를 들어, 인터페이스가 있어야지 @Transactional
이런 어노테이션이 동작이 가능하기 때문이다. (AOP Proxy 만들어서 트랜잭션을 처리하기 때문)
특정 버전부터 CGLIB 라이브러리를 사용하여, 클래스 기반으로 AOP Proxy 를 만들도록 지원을 하게 되었다.
Spring 환경설정을 통해 AOP Proxy를 만드는 방식을 개발자가 선택 할 수 있게 되었다.
spring.aop.proxy-target-class=true
결론
대부분의 Spring 프로젝트에서 Service 가 하나의 인터페이스에 하나의 구현체로 있는 것이 대부분이였기에 필요성이 사라짐
https://dimitr.im/spring-interface https://velog.io/@hsw0194/Spring-Boot에서-interface를-사용해야-할까 https://hyunsoori.tistory.com/11