設定ファイル
Spring Bootの設定ファイル
Section titled “Spring Bootの設定ファイル”Spring Bootでは、application.propertiesまたはapplication.ymlを使用してアプリケーションの設定を行います。この章では、設定ファイルの使い方と実践的な設定例について詳しく解説します。
設定ファイルの種類
Section titled “設定ファイルの種類”Spring Bootでは、以下の順序で設定ファイルが読み込まれます(後のものが優先):
application.properties/application.ymlapplication-{profile}.properties/application-{profile}.yml- 環境変数
- コマンドライン引数
application.properties vs application.yml
Section titled “application.properties vs application.yml”application.properties
Section titled “application.properties”特徴:
- シンプルで読みやすい
- キー=値の形式
- ネストした設定はドット(.)で表現
例:
# サーバー設定server.port=8080server.servlet.context-path=/api
# データベース設定spring.datasource.url=jdbc:postgresql://localhost:5432/mydbspring.datasource.username=myuserspring.datasource.password=mypasswordspring.datasource.driver-class-name=org.postgresql.Driver
# JPA設定spring.jpa.hibernate.ddl-auto=updatespring.jpa.show-sql=truespring.jpa.properties.hibernate.format_sql=true
# ロギング設定logging.level.com.example.myapp=DEBUGlogging.level.root=INFOapplication.yml
Section titled “application.yml”特徴:
- 階層構造が視覚的に分かりやすい
- YAML形式(インデントで階層を表現)
- コメントが書きやすい
例:
# サーバー設定server: port: 8080 servlet: context-path: /api
# データベース設定spring: datasource: url: jdbc:postgresql://localhost:5432/mydb username: myuser password: mypassword driver-class-name: org.postgresql.Driver
# JPA設定 jpa: hibernate: ddl-auto: update show-sql: true properties: hibernate: format_sql: true
# ロギング設定logging: level: com.example.myapp: DEBUG root: INFOどちらを使うべきか:
- application.properties: シンプルな設定、既存プロジェクトとの互換性
- application.yml: 複雑な設定、視覚的な階層構造が重要
基本的な設定項目
Section titled “基本的な設定項目”サーバー設定
Section titled “サーバー設定”# ポート番号server.port=8080
# コンテキストパスserver.servlet.context-path=/api
# セッション設定server.servlet.session.timeout=30mserver.servlet.session.cookie.name=MYAPP_SESSION
# エラーページの設定server.error.whitelabel.enabled=falseserver.error.include-message=alwaysserver.error.include-stacktrace=on_paramデータベース設定
Section titled “データベース設定”# PostgreSQLspring.datasource.url=jdbc:postgresql://localhost:5432/mydbspring.datasource.username=myuserspring.datasource.password=mypasswordspring.datasource.driver-class-name=org.postgresql.Driver
# コネクションプール設定(HikariCP)spring.datasource.hikari.maximum-pool-size=10spring.datasource.hikari.minimum-idle=5spring.datasource.hikari.connection-timeout=30000spring.datasource.hikari.idle-timeout=600000spring.datasource.hikari.max-lifetime=1800000
# JPA設定spring.jpa.hibernate.ddl-auto=updatespring.jpa.show-sql=truespring.jpa.properties.hibernate.format_sql=truespring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialectspring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=trueロギング設定
Section titled “ロギング設定”# ログレベルlogging.level.root=INFOlogging.level.com.example.myapp=DEBUGlogging.level.org.springframework.web=INFOlogging.level.org.hibernate.SQL=DEBUG
# ログファイルlogging.file.name=logs/application.loglogging.file.max-size=10MBlogging.file.max-history=30
# ログパターンlogging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %msg%nlogging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%nプロファイル別の設定
Section titled “プロファイル別の設定”プロファイルの指定
Section titled “プロファイルの指定”コマンドラインから:
# 開発環境java -jar myapp.jar --spring.profiles.active=dev
# 本番環境java -jar myapp.jar --spring.profiles.active=prod環境変数から:
export SPRING_PROFILES_ACTIVE=prodapplication.propertiesから:
spring.profiles.active=devプロファイル別の設定ファイル
Section titled “プロファイル別の設定ファイル”application-dev.properties(開発環境):
# 開発環境用設定server.port=8080
spring.datasource.url=jdbc:h2:mem:testdbspring.datasource.driver-class-name=org.h2.Driverspring.jpa.hibernate.ddl-auto=create-dropspring.jpa.show-sql=true
logging.level.com.example.myapp=DEBUGapplication-prod.properties(本番環境):
# 本番環境用設定server.port=8080
spring.datasource.url=jdbc:postgresql://prod-db:5432/mydbspring.datasource.username=${DB_USERNAME}spring.datasource.password=${DB_PASSWORD}
spring.jpa.hibernate.ddl-auto=validatespring.jpa.show-sql=false
logging.level.com.example.myapp=INFOlogging.level.root=WARNapplication.ymlでのプロファイル設定:
spring: profiles: active: dev
---# 開発環境spring: config: activate: on-profile: dev
server: port: 8080
spring: datasource: url: jdbc:h2:mem:testdb driver-class-name: org.h2.Driver jpa: hibernate: ddl-auto: create-drop show-sql: true
logging: level: com.example.myapp: DEBUG
---# 本番環境spring: config: activate: on-profile: prod
server: port: 8080
spring: datasource: url: jdbc:postgresql://prod-db:5432/mydb username: ${DB_USERNAME} password: ${DB_PASSWORD} jpa: hibernate: ddl-auto: validate show-sql: false
logging: level: com.example.myapp: INFO root: WARN環境変数とプレースホルダー
Section titled “環境変数とプレースホルダー”環境変数の使用
Section titled “環境変数の使用”機密情報(パスワード、APIキーなど)は環境変数から読み込むことが推奨されます。
# 環境変数から読み込みspring.datasource.username=${DB_USERNAME}spring.datasource.password=${DB_PASSWORD}
# デフォルト値を指定server.port=${PORT:8080}
# ネストした環境変数app.api.base-url=${API_BASE_URL:https://api.example.com}プレースホルダーの使用
Section titled “プレースホルダーの使用”# 他のプロパティを参照app.name=My Applicationapp.description=${app.name} - Version ${app.version:1.0.0}カスタムプロパティの定義と使用
Section titled “カスタムプロパティの定義と使用”カスタムプロパティの定義
Section titled “カスタムプロパティの定義”# カスタム設定app.name=My Applicationapp.version=1.0.0app.api.base-url=https://api.example.comapp.api.timeout=5000
# リスト形式app.allowed.ips=192.168.1.1,192.168.1.2,192.168.1.3
# マップ形式app.features.enabled=trueapp.features.max-users=100@ConfigurationPropertiesを使用
Section titled “@ConfigurationPropertiesを使用”設定クラスの作成:
@Configuration@ConfigurationProperties(prefix = "app")@Datapublic class AppProperties {
private String name; private String version; private Api api = new Api(); private List<String> allowedIps = new ArrayList<>(); private Features features = new Features();
@Data public static class Api { private String baseUrl; private int timeout; }
@Data public static class Features { private boolean enabled; private int maxUsers; }}使用例:
@Servicepublic class ApiService {
private final AppProperties appProperties;
public ApiService(AppProperties appProperties) { this.appProperties = appProperties; }
public void callExternalApi() { String baseUrl = appProperties.getApi().getBaseUrl(); int timeout = appProperties.getApi().getTimeout();
// API呼び出し... }}@Valueを使用
Section titled “@Valueを使用”@Servicepublic class UserService {
@Value("${app.name}") private String appName;
@Value("${app.api.base-url}") private String apiBaseUrl;
@Value("${app.api.timeout:5000}") // デフォルト値5000 private int apiTimeout;
@Value("${app.allowed.ips}") private List<String> allowedIps;}外部設定ファイルの読み込み
Section titled “外部設定ファイルの読み込み”外部設定ファイルの指定
Section titled “外部設定ファイルの指定”# コマンドラインからjava -jar myapp.jar --spring.config.location=classpath:/application.properties,file:/path/to/config/application.properties
# またはjava -jar myapp.jar --spring.config.additional-location=file:/path/to/config/設定ファイルの優先順位
Section titled “設定ファイルの優先順位”- コマンドライン引数
SPRING_APPLICATION_JSON環境変数java:comp/envのJNDI属性- Javaシステムプロパティ(
System.getProperties()) - OS環境変数
application-{profile}.properties(プロファイル別)application.properties(デフォルト)
@Validatedと@Validを使用
Section titled “@Validatedと@Validを使用”@Configuration@ConfigurationProperties(prefix = "app")@Validatedpublic class AppProperties {
@NotBlank private String name;
@Min(1) @Max(10000) private int maxUsers;
@Valid private Api api = new Api();
@Data public static class Api { @NotBlank @URL private String baseUrl;
@Min(1000) @Max(60000) private int timeout; }}よくある設定例
Section titled “よくある設定例”完全なapplication.properties例
Section titled “完全なapplication.properties例”# ============================================# サーバー設定# ============================================server.port=8080server.servlet.context-path=/apiserver.servlet.session.timeout=30mserver.error.whitelabel.enabled=false
# ============================================# データベース設定# ============================================spring.datasource.url=jdbc:postgresql://localhost:5432/mydbspring.datasource.username=${DB_USERNAME:myuser}spring.datasource.password=${DB_PASSWORD:mypassword}spring.datasource.driver-class-name=org.postgresql.Driver
# HikariCP設定spring.datasource.hikari.maximum-pool-size=10spring.datasource.hikari.minimum-idle=5spring.datasource.hikari.connection-timeout=30000
# ============================================# JPA設定# ============================================spring.jpa.hibernate.ddl-auto=updatespring.jpa.show-sql=truespring.jpa.properties.hibernate.format_sql=truespring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
# ============================================# ロギング設定# ============================================logging.level.root=INFOlogging.level.com.example.myapp=DEBUGlogging.file.name=logs/application.loglogging.file.max-size=10MBlogging.file.max-history=30
# ============================================# カスタム設定# ============================================app.name=My Applicationapp.version=1.0.0app.api.base-url=https://api.example.comapp.api.timeout=5000Spring Bootの設定ファイルのポイント:
- application.properties / application.yml: 設定ファイルの形式
- プロファイル: 環境別の設定を分離
- 環境変数: 機密情報の管理
- @ConfigurationProperties: 型安全な設定の読み込み
- @Value: 個別のプロパティの読み込み
- 設定の優先順位: 複数の設定ソースの優先順位を理解
適切な設定ファイルの管理により、環境ごとに異なる設定を柔軟に管理できます。