이번 편의 목표: application.properties에 적은 숫자를 빈의 생성자에서 읽습니다.
포트 번호나 하루 연체료처럼 코드에 박아 두면, 환경이 바뀔 때마다 컴파일이 필요합니다. 스프링 부트는 src/main/resources/application.properties를 시작 때 읽습니다.
속성 추가
파일에 다음 한 줄을 넣습니다.
library.daily-fee=100
키는 영문과 하이픈으로 적었습니다. 100은 종이책 하루 연체료입니다. 자바 기초의 계산 규칙과 같은 값입니다.
값 주입
FeePolicy.java를 추가합니다.
package com.thinktree.library;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class FeePolicy {
private final int dailyFee;
public FeePolicy(@Value("${library.daily-fee}") int dailyFee) {
this.dailyFee = dailyFee;
}
public int fee(int lateDays) {
return lateDays * dailyFee;
}
}@Value는 설정 키의 값을 그 매개변수에 넣습니다. 키가 없으면 애플리케이션이 시작되지 않습니다. 오타를 일찍 알게 됩니다.
HelloController가 FeePolicy도 받도록 파일 전체를 바꿉니다. 03편의 /hello는 그대로 둡니다.
package com.thinktree.library;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
private final Greeting greeting;
private final FeePolicy feePolicy;
public HelloController(Greeting greeting, FeePolicy feePolicy) {
this.greeting = greeting;
this.feePolicy = feePolicy;
}
@GetMapping("/hello")
public String hello() {
return greeting.hello();
}
@GetMapping("/fee")
public String fee() {
return "3일 연체료는 " + feePolicy.fee(3) + "원입니다.";
}
}http://localhost:8080/fee 의 응답은 3일 연체료는 300원입니다. 가 됩니다. properties의 100을 50으로 바꾸고 서버를 다시 실행하면 150원으로 바뀝니다. 자바 계산 코드는 수정하지 않았습니다.
직접 해 보기
library.daily-fee를 200으로 바꾼 뒤 /fee 응답이 600원인지 확인하세요. 확인 후에는 다시 100으로 되돌립니다.
해설
3일 곱하기 200원은 600원입니다. 설정 파일을 바꾸면 프로세스를 다시 시작해야 이 예제에는 반영됩니다. 실행 중인 서버가 파일을 자동으로 다시 읽지는 않습니다.
COMMENTS
댓글 0
이 글에 대한 의견이나 질문을 남겨 주세요.
댓글은 구글이나 카카오로 시작한 뒤에 남길 수 있습니다.
등록된 댓글이 없습니다.