Spring - $ \ {} ne fonctionne pas dans @Value

Spring - $ \ {} ne fonctionne pas dans @Value

Un exemple simple de Spring@PropertySourcepour lire un fichier de propriétés.

db.properties

db.driver=oracle.jdbc.driver.OracleDriver

AppConfig.java

@Configuration
@PropertySource("classpath:db.properties")
public class AppConfig {

    @Value("${db.driver}")
    private String driver;

Mais l'espace réservé de propriété${} est incapable de résoudre en@Value, si vous affichez la variabledriver, il affichera directement la chaîne${db.driver}, au lieu de «oracle.jdbc.driver .OracleDriver ».

Solution

Pour résoudre${} dans Spring@Value, vous devez déclarer manuellement un beanSTATICPropertySourcesPlaceholderConfigurer. Par exemple :

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();
    }
}

Pour la configuration XML, Spring vous aidera à enregistrerPropertySourcesPlaceholderConfigurer automatiquement.

Note
Lire ce printemps JIRASPR-8539

Note
Vous pouvez vous intéresser à ceSpring @PropertySource example