OOP에서 객체간 협력은 필수적이며, 객체가 협력한다는 것은 의존성이 존재한다는 것이다. 여기서 의존성이란 파라미터나 리턴값 또는 지역변수 등으로 다른 객체를 참조하는 것을 의미한다.
예들 들어 Service가 Repository를 사용하고 있을 때 Service객체가 Repository객체에 의존성이 있다고 표현한다.
여기서 두 객체간의 관계를 맺어주는 것을 의존성 주입이라고 한다.
컴파일 의존성 (구체 클래스에 의존)
런타임 의존성 (추상 클래스나 인터페이스에 의존)
@Controller
public class TestController {
private final TestServicetestService;
public TestController(TestService testService) {
this.testService= testService;
}
}
@Service
class TestService{}
@Controller
public class TestController {
@Autowired
private TestServicetestService;
}
@Service
class TestService{}
@Controller
public class TestController {
private TestServicetestService;
public void getTestService(TestService testService) {
this.testService= testService;
}
}
@Service
class TestService{}
사용하는 자원에 따라 동작이 달라지는 클래스는 정적 유틸리티 클래스나 싱글톤은 적합하지 않다. → 인스턴스를 생성할 때 생성자에 필요한 자원을 넘겨준다.
참조
이펙티브 자바