春– $ \ {}は@Valueで機能していません
プロパティファイルを読み取るための単純なSpring@PropertySource
の例。
db.properties
db.driver=oracle.jdbc.driver.OracleDriver
AppConfig.java
@Configuration @PropertySource("classpath:db.properties") public class AppConfig { @Value("${db.driver}") private String driver;
ただし、プロパティプレースホルダー${}
は@Value
で解決できません。driver
変数を出力すると、「oracle.jdbc.driver」ではなく文字列${db.driver}
が直接表示されます。 .OracleDriver」。
溶液
Spring@Value
の${}
を解決するには、STATICPropertySourcesPlaceholderConfigurer
Beanを手動で宣言する必要があります。 例えば :
AppConfig.java
import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; @Configuration @PropertySource("classpath:db.properties") public class AppConfig { @Value("${db.driver}") private String driver; @Bean public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() { return new PropertySourcesPlaceholderConfigurer(); } }
XML構成の場合、SpringはPropertySourcesPlaceholderConfigurer
を自動的に登録するのに役立ちます。
Note
この春のJIRAを読むSPR-8539
Note
このSpring @PropertySource exampleに興味があるかもしれません