장 실습: 내보내기 기능을 스타터처럼 만들기
내보내기 기능을 핵심 인터페이스와 자동 구성으로 나누고, 외부 설정 검증과 기능 활성화를 테스트와 실행 JAR의 응답으로 확인합니다.
앞 글에서는 여러 설정을 객체 하나로 받고 잘못된 값이 시작을 막게 했습니다. 이번에는 이 설정 검증을 자동 구성과 묶어, 게시글 내보내기 기능을 속성으로 켜고 끄는 부품으로 만듭니다. 실제로 전송하지 않고 설정이 어떻게 적용됐는지만 알려 주는 과제입니다.
이 글을 읽고 나면 다음을 할 수 있습니다.
- Spring에 의존하지 않는 핵심 인터페이스와 자동 구성 클래스를 나눕니다.
- 기능을 켰을 때만 설정을 바인딩하고 검증하게 만듭니다.
- 같은 실행 JAR을 인자만 바꿔 띄우고 응답을 비교합니다.
시작 상태
14장까지 이어 온 board 프로젝트를 씁니다. 사용자 정의 스타터의 자동 구성 등록 파일에 BoardClockAutoConfiguration과 BoardObserveAutoConfiguration이 적혀 있고, 앞 글의 검증 스타터가 build.gradle에 들어 있어야 합니다. 검증 스타터를 아직 넣지 않았다면 다음 줄을 dependencies 블록에 추가합니다.
implementation 'org.springframework.boot:spring-boot-starter-validation'파일은 같은 프로젝트의 board.export, board.export.autoconfigure, board.web 패키지에 추가합니다. 자동 구성의 조건은 14-6, 빈이 없을 때도 컨트롤러를 만드는 ObjectProvider는 14-7을 참고합니다. 명령은 프로젝트 루트에서 실행하고, Windows PowerShell에서는 ./gradlew를 .\gradlew.bat, curl을 curl.exe로 바꿉니다.
완성 조건
- 핵심:
board.export.BoardExporter인터페이스에String describe()하나가 있습니다. Spring에 의존하지 않습니다. - 설정:
board.export.autoconfigure.BoardExportProperties는 접두사board.export아래의endpoint,connect-timeout,read-timeout,batch-size를 받습니다. 주소와 두 타임아웃은 필수, 배치 크기는 1에서 500 사이, 주소는https, 읽기 타임아웃은 연결 타임아웃보다 짧을 수 없습니다. - 자동 구성:
board.export.enabled=true일 때만 적용되고, 사용자의BoardExporter빈이 없으면describe()가export to 주소 batch=배치크기를 돌려주는 기본 빈을 등록합니다. - 등록 파일에 자동 구성을 더합니다.
GET /export는 내보내기가 꺼져 있으면disabled, 켜져 있으면describe()의 값을 돌려줍니다.- 테스트는 꺼진 경우, 켜진 경우,
http주소를 준 경우를 확인합니다.
1단계: 핵심과 자동 구성을 테스트로 연결하기
BoardExporter, BoardExportProperties, BoardExportAutoConfiguration과 BoardExportAutoConfigurationTest를 아래 완성 파일의 경로에 만듭니다. 설정을 받는 레코드에는 앞 글처럼 필수 여부와 배치 크기 제약을 붙이고, 생성자에서 주소의 스킴과 두 타임아웃의 관계를 검사합니다. 자동 구성 클래스에 @EnableConfigurationProperties를 붙여 구성이 적용될 때만 설정을 바인딩합니다.
./gradlew test --tests board.export.BoardExportAutoConfigurationTest체크포인트: 세 테스트가 모두 통과합니다. 기능이 꺼져 있으면 설정 없이도 컨텍스트가 시작되고 BoardExporter 빈은 없습니다. 기능을 켜고 올바른 값을 주면 기본 빈의 describe()는 export to https://export.internal batch=100을 돌려줍니다. http 주소를 주면 컨텍스트 시작 실패를 확인하는 테스트가 통과합니다.
2단계: 등록 파일과 컨트롤러를 연결하기
src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports의 기존 두 줄 아래에 board.export.autoconfigure.BoardExportAutoConfiguration을 추가합니다. ExportController는 ObjectProvider<BoardExporter>로 빈을 받아, 빈이 없으면 disabled를 돌려주도록 만듭니다.
./gradlew bootJar
java -jar build/libs/board-0.0.1-SNAPSHOT.jar다른 터미널에서 응답을 확인합니다.
curl http://localhost:8080/export체크포인트: 응답은 disabled입니다. 내보내기 설정이 없어도 서버가 뜬 것은 속성 조건이 맞지 않아 자동 구성과 함께 설정 바인딩까지 건너뛰었기 때문입니다.
3단계: 같은 JAR을 인자로 켜기
첫 실행을 Ctrl+C로 멈춘 뒤, 같은 JAR에 내보내기 설정을 인자로 넘깁니다.
java -jar build/libs/board-0.0.1-SNAPSHOT.jar --board.export.enabled=true --board.export.endpoint=https://export.internal --board.export.connect-timeout=1s --board.export.read-timeout=3s --board.export.batch-size=100같은 curl 요청을 보냅니다. 체크포인트: 응답은 export to https://export.internal batch=100입니다. JAR을 다시 만들지 않고도 인자만으로 기능이 켜지고 설정이 적용되었습니다.
다를 때 먼저 볼 곳
| 증상 | 확인할 곳 |
|---|---|
| 꺼진 경우에도 필수 설정이 없다는 오류로 시작하지 못함 | @EnableConfigurationProperties를 속성 조건이 붙은 자동 구성 클래스에 뒀는지 |
테스트는 통과하지만 켠 JAR의 응답은 disabled | 자동 구성 등록 파일에 BoardExportAutoConfiguration의 전체 이름을 추가했는지 |
| 꺼진 경우 컨트롤러 생성이 실패함 | BoardExporter를 직접 요구하지 않고 ObjectProvider로 받는지 |
http 주소의 실패를 예상한 테스트가 실패함 | BoardExportProperties 생성자가 https 스킴을 검사하는지 |
| 둘째 서버를 띄울 때 포트를 사용할 수 없다는 오류 | 첫 서버를 Ctrl+C로 멈췄는지 |
완성 파일 전체
핵심·설정·자동 구성·컨트롤러·테스트 전체 보기
package board.export;
public interface BoardExporter {
String describe();
}package board.export.autoconfigure;
import java.net.URI;
import java.time.Duration;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
@Validated
@ConfigurationProperties("board.export")
public record BoardExportProperties(
@NotNull URI endpoint,
@NotNull Duration connectTimeout,
@NotNull Duration readTimeout,
@Min(1) @Max(500) int batchSize
) {
public BoardExportProperties {
if (endpoint != null && !"https".equals(endpoint.getScheme())) {
throw new IllegalArgumentException("endpoint must use https");
}
if (connectTimeout != null && readTimeout != null
&& readTimeout.compareTo(connectTimeout) < 0) {
throw new IllegalArgumentException(
"readTimeout must not be shorter than connectTimeout");
}
}
}package board.export.autoconfigure;
import board.export.BoardExporter;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
@AutoConfiguration
@ConditionalOnProperty(
prefix = "board.export",
name = "enabled",
havingValue = "true",
matchIfMissing = false)
@EnableConfigurationProperties(BoardExportProperties.class)
public class BoardExportAutoConfiguration {
@Bean
@ConditionalOnMissingBean(BoardExporter.class)
BoardExporter boardExporter(BoardExportProperties properties) {
return () -> "export to " + properties.endpoint()
+ " batch=" + properties.batchSize();
}
}board.autoconfig.BoardClockAutoConfiguration
board.observe.autoconfigure.BoardObserveAutoConfiguration
board.export.autoconfigure.BoardExportAutoConfigurationpackage board.web;
import board.export.BoardExporter;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ExportController {
private final ObjectProvider<BoardExporter> exporter;
public ExportController(ObjectProvider<BoardExporter> exporter) {
this.exporter = exporter;
}
@GetMapping("/export")
public String export() {
BoardExporter found = exporter.getIfAvailable();
return found == null ? "disabled" : found.describe();
}
}package board.export;
import board.export.autoconfigure.BoardExportAutoConfiguration;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import static org.assertj.core.api.Assertions.assertThat;
class BoardExportAutoConfigurationTest {
private final ApplicationContextRunner runner =
new ApplicationContextRunner().withConfiguration(
AutoConfigurations.of(BoardExportAutoConfiguration.class));
private ApplicationContextRunner enabled(String endpoint) {
return runner.withPropertyValues(
"board.export.enabled=true",
"board.export.endpoint=" + endpoint,
"board.export.connect-timeout=1s",
"board.export.read-timeout=3s",
"board.export.batch-size=100");
}
@Test
void 켜지_않으면_설정이_없어도_시작하고_빈은_없다() {
runner.run(context -> {
assertThat(context).hasNotFailed();
assertThat(context).doesNotHaveBean(BoardExporter.class);
});
}
@Test
void 켜고_올바른_값을_주면_기본_빈이_설정을_쓴다() {
enabled("https://export.internal").run(context ->
assertThat(context.getBean(BoardExporter.class).describe())
.isEqualTo("export to https://export.internal batch=100"));
}
@Test
void http_주소는_시작을_막는다() {
enabled("http://export.internal")
.run(context -> assertThat(context).hasFailed());
}
}더 해 보기
production프로필 문서에board.export설정을 넣어 프로필만으로 내보내기를 켜 보세요.--debug보고서에서BoardExportAutoConfiguration이 꺼졌을 때와 켜졌을 때 어느 묶음에 있는지 비교하세요.- 읽기 타임아웃이 연결 타임아웃보다 짧을 때 시작이 막히는지 테스트를 더해 확인하세요.
이것으로 14장을 마칩니다. 다음 장의 Actuator 엔드포인트부터는 이렇게 띄운 애플리케이션의 상태와 지표를 운영 환경에서 들여다보는 방법을 다룹니다.