動的なプロパティ名でプロパティを読み取り

src配下(Mavenの場合src.main.resources配下)app.propertiesの内容:

weapon.price.1=1000
weapon.price.2=2500

前回紹介された「@Value("${プロパティ名}")」の方法では、プロパティ名は動的に変更できませんので、新たな方法が必要です。

Java Configより定義

@Bean
public PropertiesFactoryBean appProperties() {
    PropertiesFactoryBean appProperties = new PropertiesFactoryBean();
    appProperties.setLocation(new ClassPathResource("app.properties"));
    return appProperties;
}

xmlより定義

<bean id="appProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="locations">
    <list>
      <value>classpath:app.properties</value>
    </list>
  </property>
</bean>

使用方法

@Autowired
private Properties appProperties;

private String getProperty(String key) {
    return appProperties.getProperty(key);
}

public int getWeaponPrice(int weaponId) {
    return Integer.parseInt(getProperty("weapon.price." + weaponId));
}