2
votes

Comment convertir le fichier @Propertysource en carte?

J'ai mon contenu dans un fichier .properties. Je charge le fichier de propriétés à l'aide de @PropertySource.

Comment puis-je obtenir le contenu du fichier de propriétés à mapper à l'aide de l'annotation @PropertySource?

Mon fichier de propriété ressemble à ceci:

XXX

Dans mon composant, je veux lire le fichier de propriétés et mettre le contenu dans une carte.

Map<String, String> myMap= new HashMap<String, String>();
Properties myProperties = new Properties();
myProperties .putAll(myMap);

J'ai essayé quelque chose comme ça, mais cela ne fonctionne pas.

@PropertySource("classpath:myData.properties")
public class myComponentService {

@Autowired
private Environment environment;

Map<String, String> myMap = new HashMap<String, String>(); //Property file content goes here

}  


4 Réponses :


0
votes

Hmm, pas sûr, ce que vous voulez faire ...

Habituellement, @PropertySource est utilisé comme ceci:

@Autowired
private Environment environment;

avec "db.url" et " db.user "étant spécifié dans" config.properties ".

Peut-être que vous devriez également vous pencher sur la classe Environment de Spring:

@Configuration
@PropertySource("classpath:config.properties")
public class DbConfig {

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

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

...


0 commentaires

0
votes

Fournissez ceci est Spring XML Configuration

@Value("${propertiesName}")

ici par vous pouvez utiliser l'annotation ci-dessous dans l'application.

<context:property-placeholder location="classpath*:database.properties,classpath*:query.properties"/>


0 commentaires

2
votes

Il existe une meilleure façon ( plus propre ) de le faire en créant un bean Propriété de configuration comme suit:

@Log4j2
@EnableConfigurationProperties
@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class);
    }

    @Bean
    CommandLineRunner run(CustomPropertiesConfig config){
       return (args)->{
           Map<String, String> connection = config.getConnection();
           if(connection.containsKey("key1")){
               log.info("holla");
           }
       };
    }

}

Et puis définissez votre carte dans application.yml (Fichier de propriétés Yaml) comme ceci:

custom:
  connection:
    key1: value1
    key2: value2

Et le dernier mais non le moindre:

@Data
@Component
@ConfigurationProperties(prefix = "custom")
public class CustomPropertiesConfig {

    private Map<String, String> connection= new HashMap<>();

}

Notez que: p >

Spring Framework fournit deux classes pratiques qui peuvent être utilisées pour charger des documents YAML. Le YamlPropertiesFactoryBean charge YAML comme Properties et YamlMapFactoryBean charge YAML sous forme de carte.

Et cela:

Les fichiers YAML ne peuvent pas être chargés à l'aide de l'annotation @PropertySource. Donc, dans le cas où vous devez charger des valeurs de cette façon, vous devez utiliser un fichier de propriétés.

Cette réponse est donc valable lorsque vous essayez de vous lier à une carte à partir d'un fichier de propriétés yaml


1 commentaires

oui, cette @ConfigurationProperties est bien meilleure et plus propre.



1
votes

donc, j'ai essayé avec les deux méthodes suivantes, elles ont toutes les deux fonctionné:

Méthode 1: le contenu de mon fichier de propriétés ressemble à ceci-

public class MyBaseClass {
private MypropConfigProperties mypropConfigProperties;

@Autowired
public void setMyProp(MypropConfigProperties mypropConfigProperties) {
this.mypropConfigProperties= mypropConfigProperties;
}
.....
log.info(this.mypropConfigProperties.getMyProp().toString()); // this does the final magic
....

Dans mon java composant:

import java.util.Map;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource("classpath:myproperty-file.properties")
@ConfigurationProperties(prefix = "search")
public class MypropConfigProperties {
 private Map<String, String> myprop;

 public Map<String, String> getMyProp() {
    return myprop;
}

public void setMyProp(Map<String, String> myprop) {
        this.myprop= myprop;
    }
}

Cela a parfaitement fonctionné comme je le souhaitais. Mais l'itération inutile dans tous les fichiers de propriétés est l'inconvénient. Le meilleur moyen consiste à utiliser l'annotation @ConfigurationProperties. Référence: [ https://www.baeldung.com / configuration-properties-in-spring-boot] [1]

Méthode 2:

  1. créer un fichier de configuration.

    import org.springframework.core.env.AbstractEnvironment;
    import org.springframework.core.env.ConfigurableEnvironment;
    import org.springframework.core.env.EnumerablePropertySource;
    import org.springframework.core.env.Environment;
    import org.springframework.core.env.MapPropertySource;
    import org.springframework.core.env.PropertySource;
    import org.springframework.beans.factory.annotation.Autowired;
    ....
    @org.springframework.context.annotation.PropertySource("classpath:myproperty-file-.properties")
    public class MyBaseClass {
        @Autowired
        private Environment environment;
    ...
    Map<String, String> myMap= new HashMap<String, String>();
        for (PropertySource<?> propertySource : ((ConfigurableEnvironment) environment).getPropertySources()) {
                                if (propertySource instanceof EnumerablePropertySource) {
                                    for (String key : ((EnumerablePropertySource) propertySource).getPropertyNames()) {
                                        if (key.startsWith("search")) {
                                            myMap.put(key.replace("search.myprop.", ""), propertySource.getProperty(key).toString());
                                        }
                                    }
                                }
                            }
    
  2. Dans votre classe java

    search.myprop.a = abc
    search.myprop.b = bcd
    search.myprop.c = def
    


0 commentaires