| この記事の要点 |
|---|
|
@PropertySource の基本
Spring の標準では application.properties しか自動読み込みしません。それ以外のカスタムプロパティファイルを読み込みたい時に @PropertySource を使います。
// resources/custom.properties
app.api.host=api.example.com
app.api.port=8080
app.api.timeout=5000
// Java 側
@Configuration
@PropertySource("classpath:custom.properties")
public class CustomConfig {
@Value("${app.api.host}")
private String apiHost;
@Value("${app.api.port}")
private int apiPort;
@Bean
public ApiClient apiClient() {
return new ApiClient(apiHost, apiPort);
}
}
複数ファイルの読み込み
@Configuration
@PropertySource({
"classpath:db.properties",
"classpath:cache.properties",
"classpath:mail.properties"
})
public class AppConfig { }
// @PropertySources で書くことも可能
@Configuration
@PropertySources({
@PropertySource("classpath:db.properties"),
@PropertySource("classpath:cache.properties")
})
public class AppConfig { }
環境別ファイル + フォールバック
@Configuration
@PropertySource("classpath:db.properties")
@PropertySource(value = "classpath:db-${spring.profiles.active}.properties",
ignoreResourceNotFound = true) // ファイルなくてもエラーにしない
public class DbConfig { }
// 起動時のプロファイル指定
// java -jar app.jar --spring.profiles.active=prod
// → db.properties + db-prod.properties (後者優先)
絶対パス / 外部ファイル
// classpath
@PropertySource("classpath:config/app.properties")
// ファイルシステムの絶対パス
@PropertySource("file:/etc/myapp/config.properties")
// URL から (HTTP)
@PropertySource("http://config-server.example.com/app.properties")
// プレースホルダ使用
@PropertySource("file:${CONFIG_DIR:/etc/myapp}/app.properties")
// 環境変数 + 絶対パス
@PropertySource("file:${user.home}/.myapp/config.properties")
YAML 読み込み(カスタム Factory)
@PropertySource はYAML をサポートしません。カスタム PropertySourceFactory を実装すれば可能:
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
Properties properties = factory.getObject();
return new PropertiesPropertySource(
Objects.requireNonNull(resource.getResource().getFilename()),
properties
);
}
}
// 使用
@Configuration
@PropertySource(value = "classpath:custom.yml", factory = YamlPropertySourceFactory.class)
public class YamlConfig { }
プロパティの取得方法
① @Value
@Value("${app.api.host}")
private String apiHost;
// デフォルト値
@Value("${app.api.host:localhost}")
private String apiHost;
// SpEL 式
@Value("#{systemProperties['user.dir']}")
private String userDir;
② Environment
@Autowired
private Environment env;
public void method() {
String host = env.getProperty("app.api.host");
int port = env.getProperty("app.api.port", Integer.class, 8080); // デフォルト値付き
boolean enabled = env.getProperty("app.feature.enabled", Boolean.class, false);
}
③ @ConfigurationProperties(推奨)
@Configuration
@PropertySource("classpath:custom.properties")
@ConfigurationProperties(prefix = "app.api")
public class ApiProperties {
private String host;
private int port;
private long timeout;
// getters/setters
}
# プロパティ: app.api.host, app.api.port, app.api.timeout が自動バインド
Spring Boot との関係
Spring Boot は application.properties / application.yml を自動的に読み込むため、ほとんどの場合 @PropertySource は不要です。
Spring Boot 標準の検索順
- コマンドライン引数:
--app.host=... - OS 環境変数:
APP_HOST=... application-{profile}.propertiesapplication.properties- カスタム
@PropertySource - デフォルト値
追加ファイルを Spring Boot に読み込ませる方法
# application.properties
spring.config.import=classpath:custom.properties
spring.config.import=optional:classpath:custom.yml # YAML も OK
# コマンドライン
java -jar app.jar --spring.config.additional-location=classpath:custom/
注意点
- YAML 非対応: 標準では .yml ファイル NG → カスタム factory が必要
- encoding 注意: 日本語含む場合は UTF-8 でファイル保存
(@PropertySource(value = "...", encoding = "UTF-8")) - 順序: 後に書いた @PropertySource が優先(上書き)
- 環境変数より弱い: OS 環境変数が常に優先される
- Spring Boot では推奨されない:
spring.config.importを使う方が良い
関連記事
子ページ
子ページはありません
人気ページ
- 1 Eclipseで「サーバーに追加または除去できるリソースがありません。」の原因と対処法
- 2 tomcat の起動 / 停止ログと catalina.log・catalina.out の違い
- 3 JavaScript で base URL を取得する方法|window.location.origin
- 4 YouTube Data API v3 エラー一覧|403・400・404 の原因と対処
- 5 Laravel エラー一覧|500/Blade/DB 接続/ルーティングの代表エラー
- 6 3Dグラフィックスのソフト一覧|Blender・Metasequoiaと用途別の選び方
- 7 Spring Frameworkのアノテーション一覧
- 8 【Spring】@Valueアノテーションとは
- 9 CATALINA_HOME の確認方法 (Linux / Mac)
- 10 【Spring】@Autowiredアノテーションとは
最近更新/作成されたページ
- Visual Studio「デザイナーを表示できません」エラーの原因と対処 2026-10-28 12:06:00
- SSH 認証に失敗しました。再試行してください の対処 2026-10-28 12:06:00
- SSH2 秘密鍵の読み込みに失敗しました の原因と対処 2026-10-28 12:06:00
- TeraTerm のよくあるエラーと対処法完全ガイド — Connection refused / 2026-10-28 12:06:00
- Visual Studio エラー一覧|コンパイルエラー・警告の確認方法と対処 2026-10-28 11:39:57
- Whitelabel Error Page の原因と消し方|Spring Boot のエラーページ 2026-10-28 11:39:57
- Eclipseで「サーバーに追加または除去できるリソースがありません。」の原因と対処法 2026-10-28 11:39:57
- SQL WHERE 句完全ガイド 2026-10-28 11:39:57
- SQL JOIN 完全ガイド (INNER/LEFT/RIGHT/FULL OUTER) 2026-10-28 11:39:57
- tomcat の起動 / 停止ログと catalina.log・catalina.out の違い 2026-10-28 10:24:23
- Tomcat の起動確認方法 5 つ|localhost:8080・ポート・プロセス・ログ 2026-10-28 10:24:23
- Oracle 19c COMMITの使い方: 暗黙コミット・自動確定・応答不明時の確認 2026-10-28 09:59:09
- Oracle 19c DELETE文|削除対象の確認・COMMIT前の判断・ROLLBACKの条件 2026-10-28 09:59:09
- Oracle 19c INSERT文|INSERT ALL・SELECT・RETURNINGとMERGEの使い分け 2026-10-28 09:59:09
- Oracle 19cのトランザクション制御|COMMIT・ROLLBACK・分離レベルと接続設定 2026-10-28 09:59:09