| この記事の要点 |
|---|
|
file: / classpath: プレフィックス
| プレフィックス | 用途 | 例 |
|---|---|---|
classpath: | クラスパス (jar 内含む) | classpath:config/app.json |
classpath*: | 複数 jar から検索 | classpath*:META-INF/spring.factories |
file: | ファイルシステム | file:/etc/myapp/config.json |
http:// / https:// | リモート URL | https://example.com/config.json |
url: | generic URL | url:ftp://... |
| プレフィックスなし | 相対パス(カレントディレクトリ) | config/app.json |
方法 1: @Value で Resource 注入
@Service
public class ConfigService {
@Value("classpath:config/app.json")
private Resource configResource;
@Value("file:/etc/myapp/secret.key")
private Resource secretResource;
public String readConfig() throws IOException {
try (InputStream is = configResource.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
return reader.lines().collect(Collectors.joining("\n"));
}
}
}
方法 2: ResourceLoader 注入
@Service
public class FileService {
@Autowired
private ResourceLoader resourceLoader;
public String loadFile(String path) throws IOException {
Resource resource = resourceLoader.getResource(path);
// path: "classpath:config/app.json"
// "file:/etc/myapp/data.txt"
// "https://example.com/data.json"
try (InputStream is = resource.getInputStream()) {
return new String(is.readAllBytes(), StandardCharsets.UTF_8);
}
}
}
方法 3: ClassPathResource 直接
// classpath: のみ
ClassPathResource resource = new ClassPathResource("config/app.json");
try (InputStream is = resource.getInputStream()) {
ObjectMapper mapper = new ObjectMapper();
AppConfig config = mapper.readValue(is, AppConfig.class);
}
// Path 指定 (Spring Boot 標準の resources/ フォルダ基準)
ClassPathResource resource = new ClassPathResource("/templates/email.html");
方法 4: ResourceUtils.getFile()
// java.io.File として取得 (開発時のみ動く、jar 内では NG)
try {
File file = ResourceUtils.getFile("classpath:config/app.json");
String content = Files.readString(file.toPath());
} catch (FileNotFoundException e) {
// jar 内では FileNotFoundException
// → 本番では getInputStream() 推奨
}
// 安全な書き方
Resource resource = new ClassPathResource("config/app.json");
String content;
try (InputStream is = resource.getInputStream()) {
content = new String(is.readAllBytes(), StandardCharsets.UTF_8);
}
方法 5: PropertyPlaceholderConfigurer / @PropertySource
@Configuration
@PropertySource("classpath:custom.properties")
@PropertySource(value = "file:${EXTERNAL_CONFIG:/etc/myapp/config.properties}",
ignoreResourceNotFound = true)
public class AppConfig { }
方法 6: spring.config.import (Spring Boot 2.4+)
# application.yml
spring:
config:
import:
- classpath:custom.properties
- file:/etc/myapp/override.yml
- optional:configserver:http://config-server
- vault://
用途別の選び方
| 用途 | 推奨 |
|---|---|
| プロパティ設定読込 | application.properties + @Value |
| テンプレート / 静的ファイル | @Value("classpath:templates/...") |
| 外部設定ファイル(環境別) | spring.config.import |
| 暗号化された秘密情報 | Vault / AWS Secrets Manager |
| 大きなデータファイル | file: + StreamingResponseBody |
InputStream vs File
// ✅ jar 内・ファイルシステム両方 OK
Resource resource = new ClassPathResource("config/app.json");
try (InputStream is = resource.getInputStream()) {
// 処理
}
// ❌ jar 内では動かない (FileNotFoundException)
File file = ResourceUtils.getFile("classpath:config/app.json");
// 一時ファイルに展開する例
Resource resource = new ClassPathResource("template.docx");
Path tempFile = Files.createTempFile("template", ".docx");
try (InputStream is = resource.getInputStream()) {
Files.copy(is, tempFile, StandardCopyOption.REPLACE_EXISTING);
}
// tempFile に対して通常の File API が使える
具体例: テンプレートファイル読込
// resources/templates/email_welcome.html を読む
@Service
public class EmailService {
@Value("classpath:templates/email_welcome.html")
private Resource welcomeTemplate;
public String renderWelcomeEmail(String userName) throws IOException {
try (InputStream is = welcomeTemplate.getInputStream()) {
String template = new String(is.readAllBytes(), StandardCharsets.UTF_8);
return template.replace("{{name}}", userName);
}
}
}
具体例: 外部 JSON 設定
// 開発: classpath、本番: 外部ファイル
@Configuration
public class ExternalConfig {
@Value("${myapp.config.path:classpath:config/default.json}")
private Resource configResource;
@Bean
public AppSettings appSettings() throws IOException {
try (InputStream is = configResource.getInputStream()) {
return new ObjectMapper().readValue(is, AppSettings.class);
}
}
}
# application.properties
myapp.config.path=file:/etc/myapp/production.json
# または環境変数: MYAPP_CONFIG_PATH=...
テスト時の差し替え
@SpringBootTest
@TestPropertySource(properties = "myapp.config.path=classpath:config/test.json")
class MyServiceTest { ... }
// または application-test.yml
myapp:
config:
path: classpath:config/test.json
関連記事
子ページ
子ページはありません
同階層のページ
- インストール(eclipseプラグイン)
- クイックスタート
- プロジェクトの作成
- Spring Bootプロジェクトの作成
- Spring Bootプロジェクトの実行
- Spring BootでHello World!
- アノテーション一覧
- DB接続設定からエンティティおよびリポジトリの作成、値の取得まで(JPA編)
- DB接続設定や値の取得(JdbcTemplate編)
- ビューから値をモデルに格納しコントローラーで受け取る方法
- コントローラーにてモデルに値を格納してビューに渡す方法
- テンプレートエンジン
- ModelとModelAndViewの違い
- AOPの使用方法
- classpath: 内部ファイルの読み込み
- file: 外部ファイルの読み込み
- CSVファイルアップロード方法(Ajax)
- CSVファイルダウンロード方法(Ajax)
- Spring Bootプロジェクトのビルドと本番環境へのデプロイ方法(内部tomcat使用)
- Application.propertiesの環境依存設定の分割方法
- JPAにおけるEntityManagerの取得方法
- JPAにおけるjava.sql.Connectionの取得方法
- エラー一覧
- jarの引数を受け取る方法
- Spring BootでGmailからメール送信
- 複数のDBに接続する設定(Spring Boot & JPA編)
- ポート番号の変更
- Basic認証の実装と特定のURLに限定する方法
- Spring SecurityのBasic認証の無効化
- 独自のエラーページを定義する方法
- プロパティファイルの値やjar実行時の引数を取得する方法
人気ページ
- 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