springboot中引用配置文件中的參數


 

 首先可以看到這是做微信登陸時候的配置,一般不會寫死都是通過配置文件獲取,所以,記載配置文件中

 

 那么怎么引用呢:

 

 可以看到直接注入的方式就可以引用了,所以看下面:

進行頁面跳轉,並且帶有參數的,

使用modelandview進行,或者采用返回一個字符串的方式進行

 

 

 

 還有中方式就是,丟在resource下面,然后進行讀取,需要工具類:

import java.io.*;
import java.net.URI;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;



public class PropertiesUtil {

    private static Properties props = null;
    private static URI uri;
    private static String fileName = "/weixinconnectconfig.properties";
    
    private static InputStream in = null;

    static {
        try {
            props = new Properties();
            InputStream fis = PropertiesUtil.class.getResourceAsStream(fileName);
            props.load(fis);
            uri = PropertiesUtil.class.getResource(fileName).toURI();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 獲取某個屬性
     */
    public static String getProperty(String key) {
        try {
            props.load(PropertiesUtil.class.getResourceAsStream(fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return props.getProperty(key);
    }

    /**
     * 獲取所有屬性,返回一個map,不常用 可以試試props.putAll(t)
     */
    @SuppressWarnings("rawtypes")
    public static Map<String, String> getAllProperty() {
        Map<String, String> map = new HashMap<String, String>();
        Enumeration enu = props.propertyNames();
        while (enu.hasMoreElements()) {
            String key = (String) enu.nextElement();
            String value = props.getProperty(key);
            map.put(key, value);
        }
        return map;
    }

    /**
     * 在控制台上打印出所有屬性,調試時用。
     */
    public static void printProperties() {
        props.list(System.out);
    }

    /**
     * 寫入properties信息
     */
    public static void writeProperties(String key, String value) {
        try {
            OutputStream fos = new FileOutputStream(new File(uri));
            props.setProperty(key, value);
            // 將此 Properties 表中的屬性列表(鍵和元素對)寫入輸出流
            props.store(fos, "『comments』Update key:" + key);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 取默認key的value
     * */
    public static String getValue(String key){
        String value = null;
        props = new Properties();
        in = PropertiesUtil.class.getResourceAsStream(fileName);
        try {
            props.load(in);
        } catch (IOException e) {
//            e.printStackTrace();
        }
        value = (String) props.get(key);
        return value;
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM