본문 바로가기
Dev/Spring

스프링 root-context.xml 동작 테스트

by vellahw 2022. 10. 27.

 

  • 스프링 4.3 버전 사용
  • STS 툴 사용

 

 

1) src/main/webapp/WEB-INF/spring/root-context.xml

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
    
    <!-- Root Context: defines shared resources visible to all other web components -->
        
        <context:component-scan base-package="org.hw.sample">
        </context:component-scan>
</beans>
cs

 

2) 테스트 클래스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package org.hw.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;
}
cs

▲ Restaurant 클래스

 

1
2
3
4
5
6
7
8
9
package org.hw.sample;
 
import org.springframework.stereotype.Component;
 
import lombok.Data;
 
@Component
@Data
public class Chef { }
cs

Chef 클래스

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package org.hw.sample;
 
import static org.junit.Assert.assertNotNull;
 
import org.junit.Test;
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 lombok.Setter;
import lombok.extern.log4j.Log4j;
 
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml")
@Log4j
public class SampleTest {
    
    @Setter(onMethod_ = {@Autowired})
    private Restaurant restaurant;
    
    @Test
    public void testExist() {
        
        assertNotNull(restaurant);
        
        log.info(restaurant);
        log.info("-------------------------------");
        log.info(restaurant.getChef());
    }
}
 
cs

테스트 클래스

 

💡. @RunWith 어노테이션 : 현재 테스트 코드가 스프링을 실행하는 역할을 할 것이라고 표시

💡. @ContextConfiguration 어노테이션과 속성값 문자열 설정: 지정된 클래스나 문자열을 이용해서 필요한 객체들을 스프링 내에 객체로 등록함(=스프링의 빈으로 등록)

사용하는 문자열은 classpath: 나 file: 을 이용할 수 있다.

💡. @Log4j : Lombok을 이용해서 로그를 기록하는 Logger를 변수로 생성

별도의 Logger 객체 선언 없이도 Log4j 라이브러리와 설정이 존재한다면 바로 사용 가능.

(Spring Legacy Project)로 생성하는 경우 기본으로 Log4j와 해당 설정이 완료되는 상태이기 때문에 별도의 처리 없이 사용 가능함

💡. @Autowired : 해당 인스턴스 변수가 스프링으로부터 자동으로 주입해 달라는 표시 

💡. @Test : JUnit에서 테스트 대상을 표시하는 어노테이션. 해당 메서드를 선택하고 JUnit Test 기능을 실행함 

💡. assertNotNull() : 변수가 null이 아니어야만 테스트가 성공한다는 것을 의미

 

Run As > Junit Test 로 실행해서 테스트 결과 확인

 

🎇 실행 결과로 알 수 있는 것

  1. Restaurant 클래스에서 객체를 생성하지 않았는데도 객체가 만들어 짐 : 스프링은 관리가 필요한 객체(Bean)을 어노테이션 등을 이용해서 객체를 생성하고 관리하는 일종의 컨테이너나 팩토리 기능을 가지고 있다.
  2. Restaurant 클래스의 @Data 어노테이션으로 Lombok을 이용해 여러 메서드가 만들어짐: Lombok은 자동으로 get/set 등을 만들어 주는데 스프링은 생성자 주입 혹은 set 주입을 이용해서 동작함. Lombok을 통해 get/set 등을 자동으로 생성하고 onMethod 속성을 이용해 작성된 set에 @Autowired 어노테이션을 추가함
  3. Restaurant 객체의 Chef 인스턴스 변수에 Chef 타입의 객체가 주입 됨 : 스프링은 @Autowired와 같은 어노테이션을 이용해 개발자가 직접 객체들과의 관게를 관리하지 않고 자동으로 관리 되도록 함

 

코드에 사용된 어노테이션들
Lombok 관련 Spring 관련 테스트 관련
@Setter @Autowired @RunWith
@Data @Component @ContextConfiguration
@Log4j   @Test

 

 

 

출처: 구멍가게 코딩단 <코드로 배우는 스프링 웹 프로젝트> 

댓글