210 lines
7.6 KiB
Markdown
210 lines
7.6 KiB
Markdown
# Spring Boot에서 application.yaml
|
|
|
|
Spring Boot는 기본적으로 `application.properties`를 제공하지만, YAML(`.yaml`) 형식이 계층 구조를 표현하기에 더 적합합니다. 실무에서 환경별 설정(개발, 운영 등)을 분리하거나 복잡한 설정을 관리할 때 유리하죠.
|
|
|
|
- **위치**: `src/main/resources/application.yaml`
|
|
- **특징**: 키-값 쌍을 계층적으로 작성, 공백으로 들여쓰기.
|
|
|
|
**실무 팁**:
|
|
- `.properties`보다 사람이 읽기 쉬운 YAML을 선호하세요.
|
|
- 환경별로 `application-dev.yaml`, `application-prod.yaml`처럼 나눠 관리하세요.
|
|
|
|
## application.yaml 예시와 주요 설정
|
|
|
|
| 옵션 | 설명 |
|
|
|---|---|
|
|
| `server.port` | 애플리케이션이 실행될 포트 지정 |
|
|
| `server.servlet.context-path` | 애플리케이션의 기본 컨텍스트 경로 지정 |
|
|
| `spring.application.name` | 애플리케이션 이름 설정 |
|
|
| `spring.profiles.active` | 활성화할 프로파일 지정 |
|
|
| `spring.datasource.url` | 데이터베이스 연결 URL 설정 |
|
|
| `spring.datasource.username` | 데이터베이스 접속 사용자명 |
|
|
| `spring.datasource.password` | 데이터베이스 접속 비밀번호 |
|
|
| `spring.datasource.driver-class-name` | 사용할 데이터베이스 드라이버 클래스 지정 |
|
|
| `spring.jpa.database-platform` | JPA가 사용할 데이터베이스 플랫폼 (예: `org.hibernate.dialect.MySQL5Dialect`) |
|
|
| `spring.jpa.hibernate.ddl-auto` | Hibernate의 자동 DDL 생성 옵션 (예: `update`, `create-drop`) |
|
|
| `spring.jpa.show-sql` | 실행되는 SQL 로그 출력 여부 (`true` / `false`) |
|
|
| `spring.jpa.properties.hibernate.format_sql` | SQL을 보기 좋게 포맷하여 출력 여부 (`true` / `false`) |
|
|
| `logging.level.[패키지명]` | 특정 패키지의 로그 레벨 설정 (예: `DEBUG`, `INFO`) |
|
|
| `spring.messages.basename` | 다국어 메시지 번들 설정 (예: `messages`) |
|
|
| `spring.thymeleaf.cache` | Thymeleaf 템플릿 캐싱 활성화 여부 (`true` / `false`) |
|
|
| `spring.mail.host` | SMTP 메일 서버 호스트 주소 |
|
|
| `spring.mail.port` | SMTP 메일 서버 포트 번호 |
|
|
| `spring.mail.username` | SMTP 메일 서버 사용자 이름 |
|
|
| `spring.mail.password` | SMTP 메일 서버 비밀번호 |
|
|
| `spring.mail.properties.mail.smtp.auth` | SMTP 인증 여부 설정 (`true` / `false`) |
|
|
| `spring.redis.host` | Redis 서버 호스트 주소 |
|
|
| `spring.redis.port` | Redis 서버 포트 번호 |
|
|
| `spring.redis.password` | Redis 서버 비밀번호 |
|
|
| `management.endpoints.web.exposure.include` | Actuator 엔드포인트 노출 범위 지정 |
|
|
| `management.endpoint.health.show-details` | Actuator의 `/health` 엔드포인트 상세 정보 출력 여부 |
|
|
|
|
|
|
```yaml
|
|
server:
|
|
port: 8080 # 애플리케이션 실행 포트
|
|
servlet:
|
|
context-path: /myapp # 기본 URL을 `/myapp`로 설정 (http://localhost:8080/myapp)
|
|
spring:
|
|
application:
|
|
name: my-app # 애플리케이션 이름
|
|
datasource: # 데이터베이스 설정
|
|
url: jdbc:h2:mem:testdb # H2 인메모리 DB 연결 설정
|
|
driver-class-name: org.h2.Driver
|
|
username: sa
|
|
password:
|
|
jpa: # JPA 설정
|
|
hibernate:
|
|
ddl-auto: update # 테이블 자동 생성 (`create`, `update`, `validate`, `none` 등)
|
|
show-sql: true # Hibernate 쿼리가 로그로 출력
|
|
thymeleaf: # Thymeleaf 설정
|
|
cache: false # 개발 시 템플릿 캐시를 비활성화하여 변경 사항 즉시 반영
|
|
messages: # 다국어(i18n) 설정
|
|
basename: messages # `messages.properties`, `messages_ko.properties` 등 다국어 파일을 설정
|
|
mail: # 이메일 설정
|
|
host: smtp.gmail.com
|
|
port: 587
|
|
username: myemail@gmail.com
|
|
password: mypassword
|
|
properties:
|
|
mail.smtp.auth: true
|
|
mail.smtp.starttls.enable: true
|
|
redis: # Redis 설정
|
|
host: localhost # Redis 서버 주소
|
|
port: 6379 # Redis 서버 포트
|
|
password: secret # Redis 접속 비밀번호
|
|
profiles: # 프로파일 설정
|
|
active: dev # `dev` 프로파일을 활성화
|
|
logging: # 로깅 설정
|
|
level:
|
|
root: INFO # 기본 로그 레벨을 INFO로 설정
|
|
com.example: DEBUG # `com.example` 패키지의 로그 레벨을 DEBUG로 설정
|
|
file:
|
|
name: logs/my-app.log # 로그 파일의 경로와 이름
|
|
management: # Spring Boot Actuator 설정
|
|
endpoints:
|
|
web:
|
|
exposure:
|
|
include: health, info # Actuator에서 `/health`, `/info` 엔드포인트 활성화
|
|
endpoint:
|
|
health:
|
|
show-details: always # `/health`에서 상세 정보 제공
|
|
---
|
|
spring:
|
|
config:
|
|
activate:
|
|
on-profile: prod
|
|
datasource:
|
|
url: jdbc:mysql://localhost:3306/mydb # MySQL 연결 URL
|
|
username: root # DB 사용자명
|
|
password: secret # DB 비밀번호. 운영 환경에서는 환경 변수(`SPRING_DATASOURCE_PASSWORD`)로 관리
|
|
driver-class-name: com.mysql.cj.jdbc.Driver #JDBC 드라이버 설정
|
|
jpa:
|
|
database-platform: org.hibernate.dialect.MySQL8Dialect # Hibernate가 사용할 데이터베이스 방언
|
|
hibernate:
|
|
ddl-auto: update
|
|
show-sql: true
|
|
properties:
|
|
hibernate:
|
|
format_sql: true # SQL을 보기 좋게 출력
|
|
```
|
|
|
|
|
|
## 다중 프로파일 설정
|
|
스프링 부트에서는 `---` (YAML 문서 구분선)을 사용하여 `application.yaml` 파일 내에서 여러 프로파일을 정의합니다. 각 섹션은 `spring.config.activate.on-profile` 속성을 통해 특정 프로파일에 연결됩니다. 실행 시 활성화된 프로파일에 해당하는 설정만 적용됩니다.
|
|
|
|
- **공통 설정**: 파일 상단에 위치하며, 모든 프로파일에서 적용됩니다.
|
|
- **프로파일별 설정**: `---`로 구분된 섹션에서 `spring.config.activate.on-profile`로 프로파일을 지정합니다.
|
|
|
|
### 기본 설정 (`application.yaml`)
|
|
```yaml
|
|
spring:
|
|
profiles:
|
|
active: dev
|
|
```
|
|
위 설정은 **`application-dev.yaml`** 파일을 활성화합니다.
|
|
`spring.profiles.active=prod`로 변경하면 운영 환경 설정이 적용됨.
|
|
|
|
### 개발 환경 (`application-dev.yaml`)
|
|
```yaml
|
|
server:
|
|
port: 8081
|
|
spring:
|
|
datasource:
|
|
url: jdbc:h2:mem:testdb
|
|
username: sa
|
|
password:
|
|
```
|
|
### 운영 환경 (`application-prod.yaml`)
|
|
```yaml
|
|
server:
|
|
port: 8080
|
|
spring:
|
|
datasource:
|
|
url: jdbc:mysql://prod-db:3306/proddb
|
|
username: admin
|
|
password: securepassword
|
|
```
|
|
|
|
### 프로파일 활성화 방법
|
|
특정 프로파일을 활성화하려면 아래 방법 중 하나를 사용합니다:
|
|
|
|
#### 실행 옵션으로 지정
|
|
JVM 실행 시 `-Dspring.profiles.active` 속성을 전달합니다.
|
|
```bash
|
|
java -jar my-app.jar -Dspring.profiles.active=dev
|
|
```
|
|
|
|
#### 환경 변수로 지정
|
|
운영 체제 환경 변수로 설정합니다.
|
|
```bash
|
|
export SPRING_PROFILES_ACTIVE=dev
|
|
java -jar my-app.jar
|
|
```
|
|
|
|
#### `application.yaml`에 기본값 설정
|
|
파일 내에서 기본 프로파일을 지정할 수 있습니다.
|
|
```yaml
|
|
spring:
|
|
profiles:
|
|
active: dev # 기본 프로파일
|
|
```
|
|
|
|
#### 코드에서 프로파일 지정
|
|
`SpringApplication`을 사용할 때 프로파일을 설정할 수 있습니다.
|
|
```java
|
|
@SpringBootApplication
|
|
public class MyApplication {
|
|
public static void main(String[] args) {
|
|
SpringApplication app = new SpringApplication(MyApplication.class);
|
|
app.setAdditionalProfiles("dev");
|
|
app.run(args);
|
|
}
|
|
}
|
|
```
|
|
|
|
|
|
## `@Value`
|
|
|
|
```java
|
|
@RestController
|
|
@RequestMapping("/api")
|
|
public class ConfigController {
|
|
|
|
@Value("${spring.application.name}")
|
|
private String appName;
|
|
|
|
@Value("${server.port}")
|
|
private int port;
|
|
|
|
@GetMapping("/config")
|
|
public Map<String, Object> getConfig() {
|
|
Map<String, Object> config = new HashMap<>();
|
|
config.put("applicationName", appName);
|
|
config.put("serverPort", port);
|
|
return config;
|
|
}
|
|
}
|
|
```
|
|
|