-
[Spring Boot] 프로젝트에서 환경변수 설정하는 방법Spring 2025. 3. 13. 17:15

1. 환경변수란?
환경변수(Environment Variables)는 운영체제에서 제공하는 동적인 값으로, 애플리케이션이 실행되는 환경에 따라 설정 값을 다르게 적용할 수 있도록 도와준다. Spring Boot 프로젝트에서도 환경변수를 활용하면 코드 수정 없이 설정을 변경할 수 있어 유지보수성과 보안성이 향상된다.
2. 환경변수를 설정하는 이유
Spring Boot에서 환경변수를 설정하면 다음과 같은 장점이 있다:
1) 보안성 강화
- 코드에 중요한 정보를 직접 포함하면 보안상 위험할 수 있다.
- 데이터베이스 비밀번호, API 키, 외부 서비스 인증 정보 등을 환경변수로 관리하면 소스 코드 유출 시에도 민감한 정보가 보호된다.
2) 운영 환경 별 설정 분리
- 개발, 테스트, 운영 환경마다 다른 설정을 쉽게 적용할 수 있다.
- 환경변수를 통해 환경별 포트, 데이터베이스 URL, 로그 레벨 등을 유연하게 조정할 수 있다.
3) 컨테이너 및 클라우드 배포 최적화
- Docker, Kubernetes와 같은 컨테이너 환경에서는 환경변수를 사용하여 설정을 관리하는 것이 일반적이다.
- Spring Boot 애플리케이션을 클라우드 서비스(AWS, GCP, Azure)에서 실행할 때 환경변수를 활용하면 배포 과정이 더욱 간편해진다.
4) 코드 수정 없이 설정 변경 가능
- application.yml 또는 application.properties 파일을 직접 수정하는 것보다 환경변수를 활용하면 코드 변경 없이 설정을 조정할 수 있다.
3. Spring Boot에서 환경변수 설정하는 방법
1) 의존성 추가
dependencies { implementation 'io.github.cdimascio:dotenv-java:3.0.0' implementation 'org.springframework.boot:spring-boot-starter-web' testImplementation 'org.springframework.boot:spring-boot-starter-test' testRuntimeOnly 'org.junit.platform:junit-platform-launcher' }2) application.yml에서 환경변수 사용
Spring Boot에서는 application.yml 파일에서 환경변수를 불러올 수 있다.
server: port: ${SERVER_PORT:8080} # 환경변수가 없으면 기본값 8080 사용3) .env 파일을 사용하여 환경변수 설정
.env 파일을 만들어 환경변수를 정의한 후, 이를 application.yml에서 불러올 수도 있다.
.env 파일
SERVER_PORT=9090application.yml 파일에서 .env 파일 불러오기
spring: config: import: optional:.env[.properties]이렇게 하면 .env 파일에 설정된 환경변수를 사용할 수 있다.
4) Spring Boot에서 환경변수 읽기
Spring Boot 애플리케이션에서 환경변수를 직접 읽을 수도 있다.
Environment 객체 활용
import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") public class TestController { private final Environment environment; public TestController(Environment environment) { this.environment = environment; } @GetMapping("/test") public String test() { return String.format("현재 서버 포트는 %s 입니다.", environment.getProperty("server.port")); } }@Value 애노테이션 활용
import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class AppConfig { @Value("${server.port:8080}") // 기본값 8080 private String serverPort; public String getServerPort() { return serverPort; } }
3. /.gitignore
... .env*git을 사용중이라면 반드시 이 설정 파일을 gitignore에 등록해야 한다.
'Spring' 카테고리의 다른 글
[Spring] Spring AI란? (0) 2025.07.08 스프링(Spring)이란 무엇인가? (1) 2025.06.18 스프링(Spring)의 역사와 탄생 배경 (2) 2025.06.18 [Spring Boot]서비스 코드를 Interface와 Class로 나누는 이유 (0) 2025.04.15 [Spring Boot]JWT 토큰을 통한 보안 구성 완전 정복 (6) 2025.04.09 - 코드에 중요한 정보를 직접 포함하면 보안상 위험할 수 있다.