IT/Spring-JSP&Servlet

[인프런] 자바 스프링 프레임워크 - DI

_하늘여우_ 2020. 3. 4. 23:56

강의: (인프런) 자바 스프링 프레임워크(renew ver.)

 

1. 의존주입 : DI (Dependency Injection)

- 일반적으로 객체 생성할 때 new 키워드를 사용하여 객체를 생성하는 방법이 있음

- 확장성이나 유연성 측면에서 보면 new 키워드 사용하는 방법보다 생성자, setter 를 사용하여 유연하게 관리하는 방법도 있음

 

2. 스프링 DI 설정

- 스프링에서는 일반적으로 applicationContext.xml 이라는 XML 파일을 통해 생성하고자 하는 객체를 정의할 수 있음

- <beans> 태그 내 <bean> 태그를 사용하여 객체 설정

- <bean> 태그는 <constructor-arg> 태그를 통해 생성 시 추가할 객체를 설정할 수 있으며, 이는 코드로 구현 시 아래와 같이 battery 처럼 설정 가능함

	public ElectronicRadioToy(Battery battery) {
		this.battery = battery ;
	}

- applicationContext.xml 파일을 사용하기 위해서는 아래와 같이 스프링 컨테이너를 만들고, getBean메소드를 통해 사용하고자 하는 객체를 가져옴

// 스프링컨테이너에 접근 (applicationContext.xml 파일 호출)
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationContext.xml") ;

// 컨테이너 내 객체(bean) 가져옴
TransportationWalk transportationWalk = ctx.getBean("tWalk", TransportationWalk.class) ;
transportationWalk.move();