(4) Spring Official Guide - Building an Application with Spring Boot

HEYDAY7·2022년 10월 26일
0

Learn Kotlin + Spring

목록 보기
5/25

Building an Application with Spring Boot

https://spring.io/guides/gs/spring-boot/

한 줄 요약

이번에는 Spring Boot가 해주는 역할이 뭔지와 더불어, 테스트에 대한 간략한 이해를 돕고, actuator 유용할 수 있는(? 아직 모르겠다.) 라이브러리를 소개해준다.

Learn What You Can Do With Spring Boot

스프링 부트 자체가 프로젝트를 구성할 때 classpath와 beans들을 보고 빠뜨린 것, 필수적이지만 설정이 미처 되어있지 않은 부분들을 자동적으로 채워줘서 비즈니스 로직에 좀 더 집중을 할 수 있게 도와주는 역할을 한다.
"automatic configuration"이라는 키워드로 더 찾아보면 될 것 같다. 더군다나 A라는 것이 필요한데, 사용자가 A를 custom하게 구현해둔다면, 이런 경우는 추가적인 작업을 해주지 않는다고 한다.

핵심은 Spring Boot가 코드를 써주거나 수정하지는 않고, application을 돌릴 때 동적으로 bean들을 연결해주는 것이다.

프로젝트 시작

가이드에 따라 그대로 진행하면 된다.

코드 작성

// HelloController.kt
@RestController
class HelloController {
    @GetMapping("/")
    fun index(): String {
        return "Greeting from Spring Boot!"
    }
}

// Application 파일
@SpringBootApplication
class BuildingAnApplicationWithSpringBootApplication {
	@Bean
	fun commandLineRunner(ctx: ApplicationContext) = CommandLineRunner {
		println("Let's inspect the beans provided by Spring Boot:")
		val beanNames = ctx.beanDefinitionNames
		Arrays.sort(beanNames)
		for (name in beanNames) {
			println(name)
		}
	}
}

fun main(args: Array<String>) {
	runApplication<BuildingAnApplicationWithSpringBootApplication>(*args)
}

이렇게 적어서 서버를 키면 가이드에서 보여주는 것처럼 아주 많은 Bean 목록을 볼 수 있는 많은 autoconfigure를 볼 수 있다.(Thanks to spring boot)

Add Unit Tests

두 종류의 테스트를 소개시켜준다. 두 방식이라고 하는 것이 옳을 수도 있겠다.

1. mock을 활용한 테스트 방식

mockMvc를 활용해서 HTTP call을 쏘고 status와 content를 ".andExpect"를 통해서 비교하는 방식
코드는 생략한다.

2. Integration 테스트 방식

@SpringBootTest random 포트와 testRestTemplate를 통해서 만드는 방식

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class HelloControllerIT(@Autowired val template: TestRestTemplate) {

    @Test
    fun getHello() {
        val response = template.getForEntity<String>("/")
        assertThat(response.body?.equals("Greeting from Spring Boot!") ?: false)
    }
}

두 방식의 차이점

설명들을 읽어보니 두 방식의 결이 다른거 같아 추가로 찾아보았다. 가장 핵심적인 차이는 Servlet Container를 사용하냐 안하냐의 차이라고 한다. 간단히 servlet은 HTTP 통신의 입구 같은 것이며, MockMvc를 활용할 경우 이를 사용하지 않고, TestRestTemplate를 활용할 경우 이를 사용한다. 따라서 후자의 경우 실제 서버가 동작하는 것처럼 테스트를 수행할 수 있다.

이를 다른 말로 바꿔 말하면 MockMVC는 서버가 자신의 API를 검증하는 느낌이고, TestRestTemplate의 경우 클라이언트가 실제로 통신하는 것 처럼 테스트를 한다는 것이며, 이 차이점은 알아두면 유용할 것 같다.

Add Production-grade Service

실제 서버를 production에 배포할 경우 여러 상태 체크를 도와주는 actuator module이 있다고 한다. 이를 프로젝트에 포함하면 /actuator/(?)의 여러 유용한 endpoint들을 제공해주고 (health, shutdown과 같이..?) 이를 잘 활용하면 좋을 순 있을 것 같다. 지금 상태에서 자세히 알아야할 지식은 아닌 것 같아 가볍게 넘어간다.

마무리

spring boot가 주는 이득이 뭔지, 테스트의 종류와 의미가 뭔지 정도를 알 수 있었던 간단하고 좋은 가이드였던 것 같다.
작성한 코드는 다음과 같다.

profile
(전) Junior Android Developer (현) Backend 이직 준비생

0개의 댓글