우당탕탕 개발자 되기
의존성 주입 테스트 -Setter 본문
예제내용
레스토랑 객체를 만들고 레스토랑에서 일하는 셰프 객체를 주입하는 예제
-셰프 클래스
package org.zerock.sample;
import org.springframework.stereotype.Component;
import lombok.Data;
@Component
@Data
public class Chef {
}
-레스토랑 클래스 : 셰프를 주입받도록 설계한다.
package org.zerock.sample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import lombok.Data;
import lombok.Setter;
@Component
@Data
public class Restaurant {
@Setter(onMethod_ = @Autowired)
private Chef chef;
}
코드가 의미하는 것은 레스토랑 객체는 셰프 타입의 객체를 필요로 한다는 상황이다.
@Component :스프링에게 해당 클래스가 스프링에서 관리해야 하는 대상임을 표시하는 어노테이션
@Setter : 자동으로 setChef()를 컴파일 시 생성
스프링 동작시 발생하는 일
-스프링이 시작하면 스프링이 사용하는 메모리 영억을 만들게 되는데 이때 이를 Context라고 한다. 스프링안에서는 ApplicationContext라는 이름의 객체가 만들어진다.
-스프링은 자신이 객체를 생성하고 관리해야 하는 객체들에 대한 설정이 필요한데 이때 이 설정이 root-context-xml 파일이다.
-root-context-xml 에 설정되어 있는 태그 내용을 통해서 패키지를 스캔
-패키지에 있는 클래스들 중에서 스프링이 사용하는 @Component 어노테이션이 존재하는 클래스의 인스턴스를 생성
-레스토랑 객체는 셰프 객체가 필요하다는 어노테이션 설정이 있으므로, 스프링은 셰프 객체의 레퍼런스를 레스토랑 객체에 주입.
테스트 코드
package org.zerock.sample.SampleTests;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runner.Runwith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringJunit4ClassRunner;
import org.zerock.sample.Restaurant;
import jdk.internal.org.jline.utils.Log;
import lombok.Setter;
import lombok.extern.log4j.Log4j;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml")
@Log4j
public class SampleTests {
@Setter(onMethod_ = {@Autowired } )
private Restaurant restaurant;
@Test
public void testExist() {
assertNotNull(restaurant);
Log.info(restaurant);
Log.info("------------------------------------------");
Log.info(restaurant.getChef());
}
}
@Runwith : 현재 테스트 코드가 스프링을 실행하는 역할을 할 것이라는 것을 표기.
@ContextConfiguration : 지정된 클래스나 문자열을 이용해서 필요한 객체들을 스프링 내에 객체로 등록하게한다.
@Log4j : Lombok을 이용해서 로그를 기록하는 Logger를 변수로 생성한다.
@Autowired : 해당 인스턴스 변수가 스프링으로부터 자동으로 주입해 달라는 표시, 스프링은 정상적으로 주입이 가능하다면 obj 변수에 레스토랑 타입의 객체를 주입하게된다.
assertNotNull : 레스토랑 변수가 null이 아니여야만 테스트가 성공한다는 것을 의미한다.
-이 테스트를 통해 알수있는 내용
1) 테스트 코드가 실행되기 위해서 스프링 프레임워크가 동작.
2) 동작하는 과정에서 필요한 객체들이 스프링에 등록.
3)의존성 주입이 필요한 객체는 자동으로 주입이 이루어짐.
'Spring' 카테고리의 다른 글
| Spring MVC-Controller(3) (0) | 2021.02.10 |
|---|---|
| Spring MVC-Controller(2) (0) | 2021.02.09 |
| Spring MVC -Controller (0) | 2021.02.09 |
| Spring MVC (0) | 2021.02.08 |
| SpringFrame Work (0) | 2021.02.04 |