Web/Spring 2019. 10. 10. 00:22

 

오늘 포스팅할 내용은 간단하게 Springboot Test이다. 아주 자세하게 다루어보진 않지만, 유용하고 자주 사용하는 부분이다. 간단하게 유닛테스트하는 내용은 이전 포스팅을 참고하고, 이번 내용은 Springboot 환경에서의 테스트 내용을 다룰것이다.

 

TDD - 테스트 주도 개발(Test Driven Development)

작성하려는 코드가 있다면 항상 먼저 어떻게 그 코드를 테스트할지 고민해야한다. 코드를 작성한 후에 어떻게 테스트할지 고민하기보다 작성할 코드를 묘사하는 테스트를 설계해야 한다. 이것이 테스트 주도 개발..

coding-start.tistory.com

 

다음 코드는 Springboot에서 빈으로 등록된 객체들을 사용할수 있게하는 테스트이다. 즉, ApplicationContext를 띄우는 것이다.

 

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
33
34
35
36
============application.properties============
test.property=test-property
==============================================
@Service
public class CommonService {
    @Autowired
    private CommonBean commonBean;
 
    public String print(){
        String result = commonBean.print();
        System.out.println(result);
        return result;
    }
}
@Component
public class CommonBean {
    @Value("${test.property}")
    private String testProperty;
    public String print(){
        System.out.println(testProperty);
        return testProperty;
    }
}
 
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestPropertyTest {
    @MockBean
    private CommonBean commonBean;
    @Autowired
    private CommonService commonService;
    @Test
    public void print(){
        commonBean.print();
    }
}
 
cs

 

위 테스트는 성공적으로 통과할 것이다. 하지만 여기서 하나 문제점이 존재한다. 만약 아주 큰 애플리케이션이라 ApplicationContext 로드에 아주 긴 시간이 걸린다면 작은 테스트를 하나 수행할때마다, 긴 시간이 걸릴 것이다. 이러할때, 우리가 테스트에 필요한 빈만 띄울수 있다. 아래 코드를 확인하자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {
        CommonService.class,
        CommonBean.class
},initializers = ConfigFileApplicationContextInitializer.class)
public class TestPropertyTest {
 
    @Autowired
    private CommonService commonService;
 
    @Test
    public void print(){
        commonService.print();
    }
 
}
cs

 

2가지 방법이 존재한다. 첫번째 방법은 @ContextConfiguration 어노테이션을 이용하는 방법이다. 인자로 빈으로 띄울 클래스를 넘긴다. 여기서 중요한것을 관련된 클래스도 모두 넣어줘야한다는 것이다. 위를 예를 들면 CommonService 클래스를 빈으로 등록할 것인데, 해당 클래스의 내용을 보면 CommonBean을 DI받고 있으므로, CommonBean도 빈으로 띄워줘야하는 것이다. 나중에 다루어볼 것이지만 위와같이 빈으로 띄울 클래스를 명시적으로 등록해도되지만, 굳이 테스트에 사용하지 않으면 Mock 빈으로 등록해주어도 된다. 두번째 인자는 initializers이다. 만약 이 인자가 없다면, CommonBean에서 @Value로 DI 받고있는 프로퍼티값을 주입받지 못한다. 즉, application.properties의 내용을 읽지 못하는 것이다. 내부적으로 @Value를 받기위한 빈이 뜨지 못해서 그런 것 같다. 이와 같은 문제를 해결하기 위해서 initializers = ConfigFileApplicationContextInitializer.class를 등록해주므로써 프로퍼티값을 읽어 올 수 있게 하였다. 

 

두번째 방법은 아래와 같다. @SpringBootTest를 이용하여 더 간단한 설정으로 SpringBoot Test를 위한 설정을 할 수 있게된다. 또한 테스트에만 사용할 프로퍼티를 정의할 수도 있다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {CommonBean.class,CommonService.class}
,properties = {"test.property=dev-property"})
public class TestPropertyTest {
 
    @Autowired
    private CommonService commonService;
 
    @Test
    public void print(){
        commonService.print();
    }
 
}
cs

 

두번째는 Mock빈을 이용하는 방법이다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {
        CommonService.class
},initializers = ConfigFileApplicationContextInitializer.class)
public class TestPropertyTest {
 
    @MockBean
    private CommonBean commonBean;
    @Autowired
    private CommonService commonService;
 
    @Test
    public void mockBeanTest(){
        given(commonBean.print()).willReturn("Test Result");
        commonService.print();
    }
 
}
cs

 

CommonService의 비즈니스 로직을 테스트하고 싶은데, 굳이 CommonBean은 띄울 필요가 없을때, 위와 같이 MockBean을 등록해서 임의로 Mock 빈이 리턴할 값을 명시할 수 있다. 위 소스는 CommonService만 테스트를 위한 빈으로 띄우는데, 내부적으로 관련있는 CommonBean은 띄우지 않고 Mock 빈으로 띄운다. 그리고 CommonBean이 리턴하는 값을 임의로 "Test Result"라는 값으로 지정해주었다. 이렇게 테스트할 빈만 집중하여 테스트가 가능해지며 사이드 코드의 양을 줄일 수 있게 된다.

 

다음은 간단하게 Controller를 테스트할 수 있는 코드이다. 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
RunWith(SpringRunner.class)
@WebMvcTest(controllers = CommonTestController.class)
@ContextConfiguration(classes = {
        CommonTestController.class,
        CommonBean.class,
        CommonService.class}
        ,initializers = ConfigFileApplicationContextInitializer.class)
public class TestControllerTest {
 
    @Autowired
    private MockMvc mockMvc;
 
    @Test
    public void resultTest() throws Exception {
        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/test/common")).andReturn();
        System.out.println(result.getResponse().getContentAsString());
    }
 
}
cs

 

굳이 스프링을 실행시키지 않고도 컨트롤러를 테스트할 수 있다. @WebMvcTest 어노테이션을 이용하여 스프링 컨트롤러 테스트가 가능한 설정을 띄워준다. 즉, MVC관련 빈만 띄워 더욱 가볍게 스프링 컨트롤러 테스트가 가능하다. 위와 같은 어노테이션도 가능하며 아래와 같은 어노테이션 설정도 사용가능하다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
@SpringBootTest(classes = {
        CommonTestController.class,
        CommonBean.class,
        CommonService.class
})
public class TestControllerTest {
 
    @Autowired
    private MockMvc mockMvc;
 
    @Test
    public void resultTest() throws Exception {
        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/test/common")).andReturn();
        System.out.println(result.getResponse().getContentAsString());
    }
 
}
cs

 

@AutoConfigureMockMvc 어노테이션을 이용하여 MVC 테스트를 위한 설정을 AutoConfiguration하게 할수 있다. 물론, MVC테스트를 위하여 내부적으로 내/외부 연동코드가 있다면 내/외부연동을 하지 않기 위해 Mock 빈등을 이용하여 테스트 가능하다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
@SpringBootTest(classes = {
        CommonTestController.class
})
public class TestControllerTest {
 
    @Autowired
    private MockMvc mockMvc;
    @MockBean
    private CommonBean commonBean;
    @MockBean
    private CommonService commonService;
 
    @Test
    public void resultTest() throws Exception {
        given(commonBean.print()).willReturn("test");
        given(commonService.print()).willReturn("test");
        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/test/common")).andReturn();
        System.out.println(result.getResponse().getContentAsString());
    }
 
}
cs

 

마지막으로 테스트만을 위한 application.properties를 사용는 방법이다. 우선, application-test.properties를 classpath 밑의 resources 폴더 안에 넣어준다.(기존 application.properties 경로와 동일) 그리고 아래와 같이 @ActiveProfile 어노테이션을 이용하여 프로파일을 이용하여 읽어올 프로퍼티파일을 명시한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
@SpringBootTest(classes = {
        CommonTestController.class,
        CommonBean.class,
        CommonService.class
})
@ActiveProfiles("test")
public class TestControllerTest {
 
    @Autowired
    private MockMvc mockMvc;
 
    @Test
    public void resultTest() throws Exception {
        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/test/common")).andReturn();
        System.out.println(result.getResponse().getContentAsString());
    }
 
}
cs

 

위 코드는 기존 application.properties가 아닌, application-test.properties 파일을 읽어 컨텍스트를 구성할 것이다.

 

아주 간단하게만 springboot test를 다루어봤는데, 추후 포스팅에서 지금까지 다룬 내용과 더 자세한 테스팅관련 기술을 다루어볼 것이다.

posted by 여성게
:
Web/Spring 2019. 8. 5. 14:43

 

이번 포스팅에서 다루어볼 내용은 spring boot project에서 DB Access관련 설정을 application.properties에 설정 해 놓는데, 기존처럼 평문으로 username/password를 넣는 것이 아니라 특정 알고리즘으로 암호화된 문자열을 넣고 애플리케이션 스타트업 시점에 복호화하여 DB Access를 하는 것입니다. 바로 예제로 들어가겠습니다.

 

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.example.demo;
 
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
 
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
 
import org.junit.Test;
 
public class EncryptTest {
 
    @Test
    public void encrypt() throws Exception {
        
        String str = "ENCRYPT!@1234";
        String encStr = encAES(str);
        System.out.println(encStr);
        System.out.println(decAES(encStr));
        
    }
    
    public Key getAESKey() throws Exception {
        String iv;
        Key keySpec;
 
        String key = "encryption!@1234";
        iv = key.substring(016);
        byte[] keyBytes = new byte[16];
        byte[] b = key.getBytes("UTF-8");
 
        int len = b.length;
        if (len > keyBytes.length) {
           len = keyBytes.length;
        }
 
        System.arraycopy(b, 0, keyBytes, 0, len);
        keySpec = new SecretKeySpec(keyBytes, "AES");
 
        return keySpec;
    }
 
    // 암호화
    public String encAES(String str) throws Exception {
        Key keySpec = getAESKey();
        String iv = "0987654321654321";
        Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
        c.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv.getBytes("UTF-8")));
        byte[] encrypted = c.doFinal(str.getBytes("UTF-8"));
        String enStr = new String(Base64.getEncoder().encode(encrypted));
 
        return enStr;
    }
 
    // 복호화
    public String decAES(String enStr) throws Exception {
        Key keySpec = getAESKey();
        String iv = "0987654321654321";
        Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
        c.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(iv.getBytes("UTF-8")));
        byte[] byteStr = Base64.getDecoder().decode(enStr.getBytes("UTF-8"));
        String decStr = new String(c.doFinal(byteStr), "UTF-8");
 
        return decStr;
    }
}
 
cs

 

위의 소스는 암복호화 단위테스트 코드입니다. AES-128 방식으로 암복호화하였으며 CBC 방식으로 진행하였습니다. 암호화 알고리즘에 대해서는 추후 포스팅하도록 하겠습니다.

 

1
2
3
#AES128_Encrypt
spring.datasource.username=T7Me97L7JW9YXubNVtNfpQ==
spring.datasource.password=/Wm/Ubs7CniQuA+5Mzq7Qg==
cs

 

위는 암호화된 형태소 Datasource 정보를 넣은 것입니다.

 

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.example.demo.config;
 
import java.security.Key;
import java.util.Base64;
import java.util.Properties;
 
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
 
public class EncryptEnvPostProcessor implements EnvironmentPostProcessor {
 
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        
        Properties props = new Properties();
        try {
            props.put("spring.datasource.password", decAES(environment.getProperty("spring.datasource.password")));
            props.put("spring.datasource.username", decAES(environment.getProperty("spring.datasource.username")));
        } catch (Exception e) {
            System.out.println("DB id/password decrypt fail !");
        }
 
        environment.getPropertySources().addFirst(new PropertiesPropertySource("myProps", props));
 
    }
    
    public Key getAESKey() throws Exception {
        String iv;
        Key keySpec;
 
        String key = "encryption!@1234";
        iv = key.substring(016);
        byte[] keyBytes = new byte[16];
        byte[] b = key.getBytes("UTF-8");
 
        int len = b.length;
        if (len > keyBytes.length) {
           len = keyBytes.length;
        }
 
        System.arraycopy(b, 0, keyBytes, 0, len);
        keySpec = new SecretKeySpec(keyBytes, "AES");
 
        return keySpec;
    }
 
    // 암호화
    public String encAES(String str) throws Exception {
        Key keySpec = getAESKey();
        String iv = "0987654321654321";
        Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
        c.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv.getBytes("UTF-8")));
        byte[] encrypted = c.doFinal(str.getBytes("UTF-8"));
        String enStr = new String(Base64.getEncoder().encode(encrypted));
 
        return enStr;
    }
 
    // 복호화
    public String decAES(String enStr) throws Exception {
        Key keySpec = getAESKey();
        String iv = "0987654321654321";
        Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
        c.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(iv.getBytes("UTF-8")));
        byte[] byteStr = Base64.getDecoder().decode(enStr.getBytes("UTF-8"));
        String decStr = new String(c.doFinal(byteStr), "UTF-8");
 
        return decStr;
    }
 
}
 
cs

 

위 소스는 springboot application 기동 시점에 암호화된 username/password를 복호화하여 Datasource 객체를 생성하기 위한 후처리 프로세서입니다. EnvironmentPostProcessor라는 인터페이스를 구현한 클래스를 하나 생성하여 오버라이딩된 메소드에 복호화하는 로직을 구현해주시면 됩니다.

 

여기서 중요한 것은 그냥 후처리 프로세서를 등록하면 끝나는 것이 아니라 설정 파일을 넣어 주어야 합니다.

 

 

src/main/resources/META-INF/spring.factories 파일을 생성하여 아래와 같은 정보를 기입해줍니다.

 

1
2
# post processor 적용
org.springframework.boot.env.EnvironmentPostProcessor=com.example.demo.config.EncryptEnvPostProcessor
cs

EncryptEnvPostProcessor라는 클래스의 패키지네임을 포함한 Full Path를 해당 설정파일에 기입해주시면 됩니다.

 

여기까지 application.properties에 암호화된 정보를 넣어 복호화하는 예제를 진행해봤습니다. 사실 Datasource 외에도 다른 설정파일에도 적용가능한 예제입니다. 활용하시길 바랍니다!

posted by 여성게
:
Web/Spring 2019. 6. 15. 21:57

 

오늘 포스팅할 내용은 개발 단계에서 없어서는 안되는 로그에 관한 포스팅입니다. 매번 sysout으로 로그를 찍는 것은 바보 같이 리소스를 낭비하는 짓이라는 것은 누구나 다 알고 계실겁니다. 저는 별소 lombok을 즐겨 사용하기에 @Slfj4 어노테이션을 자주 사용하게 됩니다. 하지만 이번에는 단순 콘솔에서만 출력하는 것이 아니라, 일자별 로그파일을 떨구어주는 설정파일에 대해 알아볼 것입니다. 바로 예제로 들어가겠습니다.(로그사용법에 대해서는 다루지 않습니다.)

 

참고로 Logback은 slf4j의 구현체이자 스프링 부트의 기본 로그 객체입니다. 기본으로 classpath에서 스프링부트가 읽어가는 파일 이름은 logback-spring.xml입니다. 물론 설정 파일명을 변경하실 수도 있습니다.

 

1
2
#logging config
logging.config=classpath:logging-config.xml
cs

 

저는 기본 설정파일명을 사용하지 않을 것이기 때문에 application.properties에 로깅 설정 파일명을 명시해줍니다.

 

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<configuration>
    <!-- Created By yeoseong_yoon -->
    <!-- 로그 경로 변수 선언 -->
    <property name="LOG_DIR" value="${user.home}/logs/app" />
    <property name="LOG_PATH" value="${LOG_DIR}/app.log"/>
    
    <!-- Console Appender -->
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>
                %-5level %d{HH:mm:ss.SSS} [%thread %F:%L] %method - %msg%n
            </pattern>
        </encoder>
    </appender>
    <!-- Rolling File Appender -->
    <appender name="ROLLING_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <!-- 파일 경로 -->
        <file>${LOG_PATH}</file>
        <!-- 출력패턴 -->
        <encoder>
            <pattern>%-5level %d{HH:mm:ss.SSS} [%thread %F:%L] %method - %msg%n</pattern>
        </encoder>
        <!-- Rolling 정책 -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- .gz,.zip 등을 넣으면 자동으로 일자별 로그파일 압축 -->
            <fileNamePattern>${LOG_DIR}/app_%d{yyyy-MM-dd}_%i.log.gz</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <!-- 파일당 최고 용량 10MB -->
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <!-- 일자별 로그파일 최대 보관주기(일단위) 
            만약 해당 설정일 이상된 파일은 자동으로 제거-->
            <maxHistory>60</maxHistory>
        </rollingPolicy>
    </appender>
 
 
    <logger name="애플리케이션패키지명(ex com.web.spring)" level="INFO"/>
 
    <root level="INFO"> <!-- DEBUG -->
        <appender-ref ref="ROLLING_FILE"/>
    </root>
</configuration>
cs

 

우선은 <property>를 이용하여 전역으로 사용할 변수명을 지정해줍니다. 이 설정파일에서는 로그파일의 경로, 로그파일 Full Path를 변수에 할당하였습니다. 그다음 중요한 설정인 <appender> 설정입니다. 로그 파일의 출력 형식을 지정해주는 설정이라고 보시면 됩니다. 사실 설정의 핵심중 하나입니다. 현재 설정에서는 console,rollingfile appender를 지정해주었습니다. 

 

Appender 종류

이름 설명
ConsoleAppender 콘솔에 로그를 찍음
FileAppender 파일에 로그를 찍음(하나의 파일에 로그를 계속 누적해서 찍음)
RollingFileAppender 여러개의 파일을 순회하면서 로그를 찍음
SMTPAppender 로그를 메일에 찍어 보냄
DBAppender DB에 로그를 찍음
기타 SocketAppender, SSLSocketAppender...  

 

패턴에 사용되는 요소

 

  • 1. %Logger{length}
  • - Logger name을 축약할 수 있다. {length}는 최대 자리 수
  • 2. %thread
  • - 현재 Thread 이름
  • 3. %-5level
  • - 로그 레벨, -5는 출력의 고정폭 값
  • 4. %msg
  • - 로그 메시지 (=%message)
  • 5. %n
  • - new line
  • 6. ${PID:-}
  • - 프로세스 아이디
  • 기타
  • %d : 로그 기록시간
  • %p : 로깅 레벨
  • %F : 로깅이 발생한 프로그램 파일명
  • %M : 로깅일 발생한 메소드의 이름
  • %l : 로깅이 발생한 호출지의 정보
  • %L : 로깅이 발생한 호출지의 라인 수
  • %t : 쓰레드 명
  • %c : 로깅이 발생한 카테고리
  • %C : 로깅이 발생한 클래스 명
  • %m : 로그 메시지
  • %r : 애플리케이션 시작 이후부터 로깅이 발생한 시점까지의 시간

 

위에 설정에서 하나 짚고 넘어갈 것이 있다면 RollingAppender의 <file>과 <fileNamePattern>이다. 일자별 로그파일을 찍기 위해 버퍼가 되는 파일이고 후자는 일자별 로그파일의 이름 패턴을 넣어주는 것이다.

 

이상 정말 간단한 Logback 설정방법을 다루어보았다. 이것보다 많은 설정들이 있을 것이다. 하지만 필자로 깊게 알지못하기에 간단한 사용법만 다루었다. 하지만 하나 중요한 사실은 로그를 남기는 것도 좋지만, 적정 레벨의 선택 그리고 포맷이다. 필자가 프로젝트를 하며 ELK를 이용하여 로그를 중앙 집중식으로 관리를 하게되었는데, 정규식패턴식과 같은 것으로 로그파일을 필터링 할 상황이 생겼다. 만약 구조화된 로그 출력이라면 정규식으로 필터링 걸기가 편할 것이지만 구조화되지 않고 애플리케이션마다 출력하는 패턴이 다르다면 필터링 하는 작업도 쉽지 않을 것이다.

posted by 여성게
:
Web/Spring 2019. 2. 21. 22:14

Springboot - CommandLineRunner(커맨드라인러너)



Springboot에서 서버 구동 시점에 초기화작업으로 무엇인가를 넣고 싶다면 사용할 수 있는 방법 중 하나가 

CommandLineRunner인터페이스를 상속받는 것이다.


@SpringBootApplication 어노테이션이 붙어있는 부트구동 클래스에 CommandLineRunner를 implements

하고 run(String... strings)를 Override한다.

그리고 해당 run()에 애플리케이션의 초기작업(빈등록 과정 등등)이후 실행할 로직을 작성해주면 된다.




예제 코드는 항공편 예약서비스 예제인데, 애플리케이션 구동 시점에 예약가능한

비행편을 알아보기위하여 검색 마이크로서비스 애플리케이션에 초기데이터를 

삽입하는 코드이다.



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
@SpringBootApplication
public class Application implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(Application.class);
    
    @Autowired
    private FlightRepository flightRepository;
    
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    @Override
    public void run(String... strings) throws Exception {
        List<Flight> flights = new ArrayList<>();
        flights.add(new Flight("BF100""SEA","SFO","22-JAN-18",new Fares("100""USD"),new Inventory(100)));
        flights.add(new Flight("BF101""NYC","SFO","22-JAN-18",new Fares("101""USD"),new Inventory(100)));
        flights.add(new Flight("BF105""NYC","SFO","22-JAN-18",new Fares("105""USD"),new Inventory(100)));
        flights.add(new Flight("BF106""NYC","SFO","22-JAN-18",new Fares("106""USD"),new Inventory(100)));
        flights.add(new Flight("BF102""CHI","SFO","22-JAN-18",new Fares("102""USD"),new Inventory(100)));
        flights.add(new Flight("BF103""HOU","SFO","22-JAN-18",new Fares("103""USD"),new Inventory(100)));
        flights.add(new Flight("BF104""LAX","SFO","22-JAN-18",new Fares("104""USD"),new Inventory(100)));
        
        flightRepository.saveAll(flights);
        
        logger.info("Looking to load flights...");
        for (Flight flight : flightRepository.findByOriginAndDestinationAndFlightDate("NYC""SFO""22-JAN-18")) {
            logger.info(flight.toString());
        }
    }
     
}
cs


만약 애플리케이션 구동 순서에 선후가 존재한다면 후행 애플리케이션에 위와같이 run()을 오버라이드하여

선행 애플리케이션에 Health Check등을 하는 로직을 넣어도 괜찮은 방법이 될 것 같다.

posted by 여성게
: