[Java] SpringBoot obtém informações de configuração no arquivo de configuração


Prefácio

Durante o processo de desenvolvimento do projeto, pode haver algumas configurações que precisam ser escritas no arquivo de configuração. Naquela época, eu não estava muito claro sobre como obter as informações do arquivo de configuração. O artigo a seguir é meu método de integração de informações on-line e integrando-o por meio de projetos reais. Espero que isso ajude a todos vocês!


1. Crie um arquivo de configuração

(1) Crie um novo arquivo xxxxxx.properties na pasta de recursos

(2) O conteúdo do arquivo é o seguinte

#签名密匙
KEY=abcdefg123456789
#1.超级管理员账户名称(可执行退款撤销操作权限)
ADMIN_JURISDICTION=admin

提示:写入的方式就是键值对方式,到时候利用工具类,填入键就可以获取到另外一遍的值的内容

2. Crie a classe de ferramenta de aquisição

código mostrado abaixo:

import com.example.whinterface.constant.PublicsConstant;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Enumeration;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 * 读取Properties中的参数
 */
public class PropertiesReader {
    
    
    private static Log log = LogFactory.getLog(PropertiesReader.class);
    private static ResourceBundle resources = null;
    private static ResourceBundle namedResources = null;

    private static void getBundle() {
    
    
        try {
    
    
            resources = ResourceBundle.getBundle("WeChatConfig", Locale.getDefault());
        } catch (MissingResourceException mre) {
    
    
            log.error(mre);
        }
    }

    private static void getNamedBundle(String filename) {
    
    
        try {
    
    
            namedResources = ResourceBundle.getBundle(filename, Locale.getDefault());
        } catch (MissingResourceException mre) {
    
    
            log.error(mre);
        }
    }

    public static String getValue(String key, String filename) {
    
    
        getNamedBundle(filename);
        try {
    
    
            return namedResources.getString(key);
        } catch (Exception e) {
    
    
            return null;
        }
    }

    private static boolean checkResources() {
    
    
        if (resources == null)
            getBundle();
        return (resources != null);
    }


    private static boolean changeToBoolean(String str) throws Exception {
    
    
        String tmp = str.toLowerCase();
        if (tmp.equals("true"))
            return true;
        else if (tmp.equals("false"))
            return false;
        else
            throw new Exception("不能找到资源文件");
    }

    public static boolean getBoolean(String key) {
    
    
        String str = getString(key);
        try {
    
    
            return changeToBoolean(str);
        } catch (Exception e) {
    
    
            return false;
        }
    }

    public static boolean getBoolean(String key, boolean defaultValue) {
    
    
        String str = getString(key);
        try {
    
    
            return changeToBoolean(str);
        } catch (Exception e) {
    
    
            return defaultValue;
        }
    }


    private static int changeToInt(String str) throws Exception {
    
    
        return Integer.parseInt(str);
    }

    public static int getInt(String key) {
    
    
        String str = getString(key);
        try {
    
    
            return changeToInt(str);
        } catch (Exception e) {
    
    
            return 0;
        }
    }

    public static int getInt(String key, int defaultValue) {
    
    
        String str = getString(key);
        try {
    
    
            return changeToInt(str);
        } catch (Exception e) {
    
    
            return defaultValue;
        }
    }


    public static String getString(String key, String defaultValue) {
    
    
        String tmp = null;
        if (checkResources()) {
    
    
            try {
    
    
                tmp = resources.getString(key);
            } catch (Exception e) {
    
    
                tmp = defaultValue;
            }
        }
        return tmp;
    }

    public static String getString(String key) {
    
    
        if (checkResources()) {
    
    
            try {
    
    
                return resources.getString(key);
            } catch (Exception e) {
    
    
                ;
            }
        }
        return null;
    }

    public static String[] getStringArray(String key) {
    
    
        if (checkResources())
            return resources.getStringArray(key);
        return null;
    }

    public static Enumeration<String> getKeys() {
    
    
        return resources.getKeys();
    }
}

提示:工具类中的WeChatConfig就是配置类的名称,根据自己创建的实际情况进行修改

2. Uso real

(1) O método de chamada é muito simples, apenas uma linha de código.
O código é o seguinte:

PropertiesReader.getString("KEY")

Desta forma, o resultado é obtido e impresso e está no arquivo de configuração: abcdefg123456789


Resumir

Por exemplo: Vou falar sobre o que foi dito acima hoje. Se houver alguma deficiência, comente abaixo para orientação. Obrigado pela sua cooperação!

おすすめ

転載: blog.csdn.net/qq_42666609/article/details/130201536