
Spring 프로파일(Profile) 완벽 가이드 – 다중 환경 설정 전략
실무 환경에서는 개발(dev), 테스트(test), 운영(prod) 등 환경별로 서로 다른 설정을 사용하는 것이 필수입니다. Spring Profile 기능을 활용하면 설정 파일을 환경에 따라 분리하고, 코드도 조건부로 실행되도록 제어할 수 있습니다. 이 글에서는 Spring의 @Profile 기능과 application.yml 기반의 다중 환경 구성 전략을 실무 중심으로 설명합니다.
1. Spring Profile이란?
Spring Profile은 설정 파일, Bean 등록, 코드 실행 등을 실행 환경(dev/test/prod)에 맞게 다르게 동작하게 하는 기능입니다. 예를 들어 로컬 환경에서는 H2, 운영 환경에서는 RDS를 사용할 수 있습니다.
2. 기본 설정 방법 – application.yml 분리
Spring Boot는 application-{profile}.yml 파일을 통해 환경별 설정을 자동으로 적용할 수 있습니다.
# application.yml
spring:
profiles:
active: dev
application:
name: profile-example
# application-dev.yml
server:
port: 8080
spring:
datasource:
url: jdbc:h2:mem:testdb
# application-prod.yml
server:
port: 8081
spring:
datasource:
url: jdbc:mysql://prod-db-url
주의: application.yml에서 spring.profiles.active를 설정하거나, 실행 시 커맨드라인 옵션으로 지정할 수 있습니다.
실행 시 프로파일 설정 방법
java -jar app.jar --spring.profiles.active=prod
3. @Profile 어노테이션 사용
Bean 등록 조건을 프로파일에 따라 다르게 지정할 수 있습니다.
@Configuration
@Profile("dev")
public class DevConfig {
@Bean
public DataSource dataSource() {
return new H2DataSource();
}
}
@Configuration
@Profile("prod")
public class ProdConfig {
@Bean
public DataSource dataSource() {
return new MysqlDataSource();
}
}
해당 프로파일이 활성화되었을 때만 해당 클래스/Bean이 등록됩니다.
4. 다중 프로파일 적용
다음과 같이 여러 프로파일을 동시에 활성화할 수도 있습니다.
spring.profiles.active=dev,local
5. 실무 적용 시 유용한 패턴
- 공통 설정은 application.yml에, 환경별 설정은 application-{profile}.yml에
- 프로파일별 로깅 설정 (logback-spring.xml)
- 운영/로컬 Bean 조건 분기 시 @Profile 사용
- 테스트 시
@ActiveProfiles("test")로 테스트 격리
6. 테스트에서 프로파일 적용
@SpringBootTest
@ActiveProfiles("test")
public class UserServiceTest {
...
}
7. 결론
Spring Profile 기능을 사용하면 환경별 설정을 분리하고, 배포 안정성을 높일 수 있습니다. 실무에서는 로컬/운영을 넘나드는 프로젝트 환경에서 설정 격리는 필수이며, 이를 가장 효과적으로 구현하는 방법이 Profile입니다. 환경별 설정을 구조화하면 유지보수성과 자동화 배포 환경에서도 강력한 이점을 얻을 수 있습니다.