15.

【Spring】@PropertySourceアノテーションとは

編集
この記事の要点
  • @PropertySource は Spring の外部プロパティファイル読み込みアノテーション
  • @Configuration クラスに付与: @PropertySource("classpath:custom.properties")
  • 読み込んだ値は @Value("${キー}")Environment で取得
  • YAML は @PropertySource 非対応 → カスタム PropertySourceFactory 実装が必要
  • Spring Boot なら通常は application.properties 自動読み込みで足りる

 

@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)

@PropertySourceYAML をサポートしません。カスタム 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 標準の検索順

  1. コマンドライン引数: --app.host=...
  2. OS 環境変数: APP_HOST=...
  3. application-{profile}.properties
  4. application.properties
  5. カスタム @PropertySource
  6. デフォルト値

追加ファイルを 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 を使う方が良い

関連記事

編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. @After
  2. @Autowired
  3. @Bean
  4. @Before
  5. @Column
  6. @Component
  7. @Configuration
  8. @Controller
  9. @Data
  10. @Entity
  11. @GeneratedValue
  12. @Id
  13. @Modifying
  14. @PathVariable
  15. @PropertySource
  16. @Repository
  17. @RequestBody
  18. @RequestMapping
  19. @ResponseBody
  20. @RestController
  21. @Service
  22. @SpringBootApplication
  23. @Table
  24. @Transactional
  25. @Value