Comment Springboot obtient la configuration dans la configuration de classe statique obtient une solution complète

  1. Comment springboot obtient-il la configuration du fichier de configuration?
  2. Comment Springboot obtient-il la configuration en classe statique?

Tous les exemples suivants sont vérifiés.

1. Définissez le format du fichier de configuration

Cela se réfère principalement aux fichiers de configuration courants: propriétés, yaml.

Bien sûr, json peut également être utilisé comme configuration, mais ce n'est pas préférable.

Fichier de configuration utilisé:

application.properties

api.key=jimo
api.password=password

application.yml

api:
  username: admin

2. Chargement par injection dynamique

2.1 @Value

@Component
public class ApiConfig {
    @Value("${api.key}")
    private String key;
    @Value("${api.username}")
    private String username;
    @Value("${api.password}")
    private String password;
}

2.2 @ConfigurationProperties (prefix = "api")

@Component
@ConfigurationProperties(prefix = "api")
public class ApiConfig {
    private String key;
    private String username;
    private String password;
}

2.3 Spécifiez le fichier de configuration @PropertySource

@PropertySourceIl s'agit d'une annotation fournie par spring pour charger des configurations spécifiques dans Environmentdes variables d'environnement. L'utilisation standard est Configurationavec.

Remarque: @PropertySource(value = {"classpath:test.conf"})Pour le même fichier, il n'a besoin d'être enregistré qu'à un seul endroit et il peut être utilisé à d'autres endroits.

Par exemple: S'inscrire dans la classe principale

@PropertySource(value = {"classpath:test.conf"})
@SpringBootApplication
public class ConfigTestApplication {

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

Peut être utilisé dans tous les autres grains:

@Component
public class Api {
    @Value("${test.a}")
    private String a;
    @Value("${test.b}")
    private String b;
}

De plus: @Valueet @ConfigurationPropertiespeut être utilisé en combinaison avec @PropertySource, faites juste attention à la duplication de la configuration causant des problèmes de couverture (après le chargement, la précédente sera couverte)

@Data
@Component
@PropertySource(value = {"classpath:test.conf"})
public class Api4Config {
    @Value("${test.a}")
    private String a;
    @Value("${test.b}")
    private String b;
}

3. Charge statique

Fait référence à la lecture du contenu du fichier de configuration dans une classe statique

3.1 Lecture directe

3.1.1 Propriétés

Nous pouvons utiliser la classe d'outils Propriétés la plus basique: c'est la manière java

import java.io.IOException;
import java.util.Properties;
import org.springframework.core.io.ClassPathResource;

/**
 * 直接读取配置文件
 *
 * @author jimo
 * @version 1.0.0
 */
public class RawConfigUtil {

    private static Properties properties = readProperties("test.conf", "test2.conf");

    private static Properties readProperties(String... confFile) {
        final Properties properties = new Properties();
        try {
            for (String path : confFile) {
                final ClassPathResource resource = new ClassPathResource(path);
                properties.load(resource.getInputStream());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties;
    }

    public static String getString(String key) {
        return properties.getProperty(key);
    }
}

3.1.2 typesafe.config

Ou par des outils tiers: https://github.com/lightbend/config lecture

        <dependency>
            <groupId>com.typesafe</groupId>
            <artifactId>config</artifactId>
            <version>1.4.0</version>
        </dependency>

Code:

import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;

/**
 * @author jimo
 * @version 1.0.0
 */
public class ConfigUtils {

    private static Config load;

    // 默认加载classpath下的application.*
    static {
        load = ConfigFactory.load();
    }

    /**
     * 读取配置文件中指定Key的值
     *
     * @param key 配置文件中的key
     * @return 指定key的value
     */
    public static String getString(String key) {
        return load.getString(key);
    }

    /**
     * 读取配置文件中指定Key的值
     *
     * @param key 配置文件中的key
     * @return 指定key的value
     */
    public static int getInt(String key) {
        return load.getInt(key);
    }

    /**
     * 读取配置文件中指定Key的值
     *
     * @param key 配置文件中的key
     * @return 指定key的value
     */
    public static boolean getBoolean(String key) {
        return load.getBoolean(key);
    }

}

Selon son introduction , ces fichiers de configuration peuvent être chargés par défaut:

system properties
application.conf (all resources on classpath with this name)
application.json (all resources on classpath with this name)
application.properties (all resources on classpath with this name)
reference.conf (all resources on classpath with this name)

La particularité est que vous pouvez lire la configuration json, mais je ne l'utilise pas beaucoup.

3.1.3 Résumé

Cependant, ces deux méthodes présentent les inconvénients suivants:

  1. Impossible de lire la configuration au format yaml
  2. Impossible d'utiliser springboot pour charger la configuration à partir de variables externes et d'environnement, donc il ne peut s'agir que d'une configuration morte, pas assez flexible

3.2 Environnement d'utilisation

Pour cibler l'environnement printanier, utilisez des outils à ressort.

EnvironmentIl représente l'environnement en cours d'exécution dans Spring, y compris: profileset properties,
il hérite de l' PropertyResolverinterface pour avoir la fonction de lire la configuration:

public interface Environment extends PropertyResolver {...}

Par conséquent, l'implémentation de la configuration est en fait PropertyResolvereffectuée par la classe d'implémentation de l' interface.

Si nous pouvons maintenir cette classe dans un environnement statique, alors vous pouvez obtenir une variable, juste au printemps pour fournir une telle interface: EnvironmentAware.

public interface EnvironmentAware extends Aware {

	/**
	 * Set the {@code Environment} that this component runs in.
	 */
	void setEnvironment(Environment environment);
}

Cette interface n'est qu'une méthode: lorsque l'environnement est prêt, elle appelle la classe d'implémentation de cette interface, puis définit l'instance.

Donc, nous implémentons cette interface pour obtenir l'environnement:

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * @author jimo
 * @version 1.0.0
 */
@Slf4j
@Component
public class MyEnvBeanUtil implements EnvironmentAware {

    private static Environment env;

    @Override
    public void setEnvironment(Environment environment) {
        env = environment;
    }

    public static String getString(String key) {
        return env.getProperty(key);
    }
}

Lorsque nous appelons:

    @Test
    void testEnv() {
        assertEquals("password", MyEnvBeanUtil.getString("api.password"));
        assertEquals("admin", MyEnvBeanUtil.getString("api.username"));
    }

3.3 继承 PropertySourcesPlaceholderConfigurer

PropertySourcesPlaceholderConfigurerRéalisé EnvironmentAware, il est donc plus riche, car vous pouvez définir les informations d'espace réservé pour les espaces réservés personnalisés. Utilisez cette méthode

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.ConfigurablePropertyResolver;
import org.springframework.core.env.PropertyResolver;
import org.springframework.stereotype.Component;

/**
 * @author jimo
 * @version 1.0.0
 */
@Component
public class PropertyUtil extends PropertySourcesPlaceholderConfigurer {

    private static PropertyResolver propertyResolver;

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess,
                                     ConfigurablePropertyResolver propertyResolver) throws BeansException {
        super.processProperties(beanFactoryToProcess, propertyResolver);
        PropertyUtil.propertyResolver = propertyResolver;
    }

    public static String getString(String key) {
        return propertyResolver.getProperty(key);
    }
}

4. Résumé

Cet article résume la configuration du ressort, principalement de la manière suivante pour obtenir la configuration du ressort:

  1. @Value
  2. @ConfigurationProperties
  3. @PropertySourceSpécifiez le fichier de configuration
  4. PropertiesLisez
  5. typesafe.configLisez
  6. EnvironmentAware
  7. PropertySourcesPlaceholderConfigurer

La configuration multi-environnement de springboot sera résumée plus loin.

A publié 80 articles originaux · Comme 319 · Visites 340 000+

Je suppose que tu aimes

Origine blog.csdn.net/jimo_lonely/article/details/105103232
conseillé
Classement