Springboot 환경변수 가져오기
개요
로컬에선 아무 문제가 없지만 배포되면 안되는 값을 관리할 때 사용할 수 있는 방법 정리.
@Value
import org.springframework.beans.factory.annotation
패키지의 Value 애노테이션으로 application.yml의 값을 가져와 사용할 수 있다.
사용 방법은 @Value("${값})
으로 값은 layer1.layer2.value와 같은 형식으로 계층을 포함하여 적어야한다.
사용시 주의할 점이 있는데 이는 빈이 생성될 때 값이 주입된다는 것으로 따라서 static 키워드가 붙으면 주입이 될 수 없다.
왜냐하면 static 필드는 클래스로딩 시점에 존재하기 때문에 빈의 생성과는 무관하기 때문이다.
또한 final 필드는 생성자에서 초기화가 강제되기에 동작하지 않는다.
해결방법으로는 @Value애노테이션을 파라미터로 넣어 생성자 주입방식으로 사용하는 것이다. 다음과 같다.
@Service
public class CalendarService {
private final String calendarId;
private final String applicationName;
public CalendarService(
@Value("${google.calendar.calendar-id}") String calendarId,
@Value("${google.calendar.application-name}") String applicationName
) {
this.calendarId = calendarId;
this.applicationName = applicationName;
}
// 메서드에서 this.calendarId 사용 가능
}
@ConfigurationProperties
다른 방법도 있는데 바로 @ConfigurationProperties
를 사용하는 것이다.
별개의 클래스를 만들고 여기서 설정파일의 값을 가져올 수 있다.
@Component
@Getter
@Setter
@ConfigurationProperties(prefix = "google.calendar")
public class GoogleCalendarProperties {
private String calendarId;
private String applicationName;
private String attendeeEmail;
}
@Service
public class CalendarService {
private final GoogleCalendarProperties properties;
public CalendarService(GoogleCalendarProperties properties) {
this.properties = properties;
}
public void doSomething() {
String calendarId = properties.getCalendarId();
}
}
후자가 더 깔끔하다.