Server

[Spring] Spring의 Ioc와 DI

lnacles 2023. 6. 15. 16:56

Spring Ioc(제어역전)와 DI(의존성 주입)에 대한 이야기입니다.

 


일반적으로 자바에서 객체를 사용하기 위해 생성자 new을 사용하여 객체를 생성한 후 객체에서 제공하는 기능을 사용합니다.

아래 코드는 일반적인 자바의 객체 생성 방식입니다.

@RestController
public class Controller {
	
    private HelloService helloService = new HelloServiceImpl();

    @GetMapping("/hello")
    public String hello() {
        return helloService.getHello();
    }
}

 

하지만 제어역전을 사용하는 스프링은 자바와 다르게 동작합니다. new 생성자로 직접 생성하지 않고 객체를 관리하는 외부로 돌립니다. 이때 객체를 관리하는 외부는 스프링 컨테이너(Spring container) 또는 IoC 컨테이너 (IoC container)입니다.

 

객체 관리를 외부 컨테이너로 위임하는 것을 제어 역전(IoC)라 합니다.

 

제어 역전으로 의존성 주입(DI)도 가능해집니다.

 

의존성 주입에는 3가지 방법이 있습니다.

  • 생성자 주입
  • 필드주입
  • setter주입

- 생성자 주입

@RestController
public class Controller {
	
    HelloService helloService
	
	@Autowired
    public Controller(HelloService helloService){
    	this.helloService = helloService;
    }
    
    @GetMapping("/hello")
    public String hello() {
        return helloService.getHello();
    }
}

 

- 필드 주입

@RestController
public class Controller {

	@Autowired
    private HelloService helloService
    
    @GetMapping("/hello")
    public String hello() {
        return helloService.getHello();
    }
}

 

- setter 주입

@RestController
public class Controller {
	
    HelloService helloService
	
	@Autowired
    public void setHelloService(HelloService helloService){
    	this.helloService = helloService;
    }
    
    @GetMapping("/hello")
    public String hello() {
        return helloService.getHello();
    }
}

 

이상 제어 역전과 의존성 주입 방법에 대해 알아봤습니다.