Springで外部設定ファイルをロードするにはどうすればよいですか?

スプリングでは、PropertyPlaceholderConfigurer、またはPropertySourcesPlaceholderConfigurerを使用して外部設定ファイルを読み込むことができます。

  1. PropertyPlaceholderConfigurer
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:config.properties"/>
</bean>

config.propertiesは外部配置文件のパス

  1. プロパティソースプレースホルダーコンフィギュレーター
@Configuration
@PropertySource("classpath:config.properties")
public class AppConfig {
// ...
}

この方式では、Spring の Java コンフィギュレーションクラスに @PropertySource アノテーションを使用し、外部コンフィギュレーションファイルのパスを指定する必要があります。

注解@ValueおよびEnvironmentオブジェクトのどちらの手法でも、外部設定ファイル内のプロパティへのインジェクションおよびアクセスが可能です。

@Value("${property.key}")
private String propertyValue;
@Autowired
private Environment env;
public void someMethod() {
String propertyValue = env.getProperty("property.key");
}
bannerAds