| この記事の要点 |
|---|
|
@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 / Maya)
- 7 Spring Frameworkのアノテーション一覧
- 8 【Spring】@Valueアノテーションとは
- 9 CATALINA_HOME の確認方法 (Linux / Mac)
- 10 【Spring】@Autowiredアノテーションとは
最近更新/作成されたページ
- プロジェクトをTomcatプロジェクトとして認識させる方法 2026-10-07 22:32:50
- MySQLの1366 Incorrect string value|Laravelの文字コード・絵文字エラー 2026-10-07 21:54:03
- curlの証明書ホスト名不一致|旧エラー51・現行60の確認と対処 2026-10-07 21:54:03
- LaravelのMassAssignmentException|fillableの原因と安全な対処 2026-10-07 21:54:03
- Eclipse で Tomcat の起動ログがコンソールに出ない時の確認手順 2026-10-07 21:54:02
- MySQLにおける中央値(Median)の導き方(バージョン8未満) 2026-10-07 13:49:45
- getInputForward 2026-10-07 13:41:15
- JSONから配列に変換 2026-10-07 13:41:15
- ビューから値をモデルに格納しコントローラーで受け取る方法 2026-10-07 13:23:41
- Laravelのテーブル作成と定義変更|マイグレーション・up/down・注意点 2026-10-07 13:23:41
- NumPy 配列に要素を追加する方法 (append / concatenate) 2026-10-07 13:23:41
- MariaDB・MySQLで現在日時を取得する方法|NOW・タイムゾーン・保存型 2026-10-07 13:13:36
- 【django】テンプレートで定数を使用する方法 2026-10-07 13:10:15
- Spring BootにおけるApplication.propertiesの環境依存設定の分割方法 2026-10-07 12:09:35
- Not supported for DML operations【Springエラー】 2026-10-07 11:09:38