Springでプロパティファイルを読み込む方法は?

Springでは設定ファイルを読み込む方法が複数あり、以下に一般的な方法の一部を示します。

  1. @Value
@Value("${config.property}")
private String property;

設定ファイル内のプロパティ値を${config.property}に設定します。

  1. ConfigurationPropertiesを使います
@Configuration
@ConfigurationProperties(prefix = "config")
public class AppConfig {
    private String property;
    // getter and setter
}

コンフィグファイル内で、config.property を介してプロパティ属性の値を設定できます。

  1. 環境
  2. 環境
@Autowired
private Environment env;

public void getProperty() {
    String property = env.getProperty("config.property");
}
  1. プロパティソースプレースホルダーコンフィギャレー
  2. ネイティブの PropertySourcesPlaceholderConfigurer
@Configuration
public class AppConfig {
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        configurer.setLocation(new ClassPathResource("config.properties"));
        return configurer;
    }
}

設定ファイル内で、${config.property}を使ってプロパティの値を参照できます。

具体的なニーズやプロジェクトの設定状況によって、一般的に設定ファイルを読み取る方法がいくつかあります。

bannerAds