春 – $ \ {}は@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で
$ {} 'を解決するには、
STATIC
` PropertySourcesPlaceholderConfigurer
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`を自動的に登録するのに役立ちます。
<util:properties location="classpath:db.properties"/>