[SpringBoot]Spring IoC(Inversion of Control)

2020. 5. 1. 13:04개발/Spring

Spring IoC(Inversion of Control)

🤔 Inversion of Control : 제어권이 역전된 것.

일반적인 경우 : 내가 사용할 의존성은 내가 만든다

IoC : 내가 사용할 의존성을 대신 만들어 준다.

의존성을 관리하는게 자기 자신이 아니라 외부에 의해 주입이 되기 떄문에 Inversion of Control 이라고 라고 부른다.

의존성을 주입해 주는 일 : Dependency Injection

😀 일반적인 경우를 보자.

// 일반적인 경우
public class TestClassController {
    public TestRespository testRespository; // 따로 초기화를 해주지 않음

    public TestClassController(TestRespository testRespository){
        this.testRespository = testRespository;
    }

    @Test
    public void testDoSomthing(){
        testRespository.save();
    }

}

위와 같은 코드가 있을때 TestRepository를 따로 초기화 해주지 않았지만,NullpointException과 같은 에러는 걱정하지 않아도 된다. 왜냐하면 TestClassController 를 만들때 생성자에서 TestRepository 객체를 주입해주기 떄문이다.

이렇게 의존성을 주입하는 일을 스프링이 대신 해주기도 하는데 아래의 코드를 보면 따로 초기화나 객체를 주입해주지 않아도 정상적으로 작동하는 것을 볼 수 있다.

// @MockBean Annotation을 사용해서 의존성을 주입
public class TestClassController {
    @MockBean
    public TestRespository testRespository; // 따로 초기화를 해주지 않음

    @Test
    public void testDoSomthing(){
        testRespository.save();
    }
}

물론 이렇게 하는 경우에 Spring에 내가 해당 TestRepositoryBean으로 만들어 사용할거다. 라는 말을 명시해주어야 한다.