[java] Spring IoC (Inversion of Control)

Spring IoC (Inversion of Control)

제어권이 뒤바뀌었다!

일반적인 (의존성에 의한) 제어권: “내가 사용할 의존성은 내가 만든다”

우리가 흔히 알고있는 방식은, 내가 사용할 의존성은 내가 직접 만드는 방식이다. (객체를 다음과 같이 직접 생성해준다던가…)

class OwnerController {
	private OwnerRepository repo = new OwnerRepository();
}

IoC: “내가 사용할 의존성? 누군가 알아서 주겠찌.. ㅇㅅㅇ”

class OwnerController {
	private OwnerRepository repo;
	
	public OwnerController(OwnerRepository repo) { // 이게 IoC. 다음과 같이 외부에서 인자로 받는다.
		this.repo = repo;	
	}
	
	// using repo...
}

bean: 스프링이 관리하는 객체들

IoC container

ApplicationConetxt: BeanFactory를 상속받음

Bean

@Autowired

@Autowired
ApplicationContext applicationContext;

@Text
public void getBean() {
	OwnerController bean = applicationContext.getBean(OwnerController.class);
	assertThat(bean).isNotNull(); // maybe true...
}