springboot 獲取所有配置檔案,包括外部配置
阿新 • • 發佈:2021-12-20
1. 使用@Value註解讀取
讀取properties配置檔案時,預設讀取的是application.properties。
@Value("${port}")
private String port;
2、使用Environment讀取
@Autowired
private Environment environment;
public void test(){
String port=environment.getProperty("port")
}
獲取全域性配置,載入jar包內部和外部的所有生效的配置
public void getEnvironment() { StandardServletEnvironment standardServletEnvironment = (StandardServletEnvironment) environment; Map<String, Map<String, String>> map = new HashMap<>(8); Iterator<PropertySource<?>> iterator = standardServletEnvironment.getPropertySources().iterator(); while (iterator.hasNext()) { PropertySource<?> source = iterator.next(); Map<String, String> m = new HashMap<>(128); String name = source.getName(); //去除系統配置和系統環境配置 if (name.equals(StandardServletEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME) || name.equals(StandardServletEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)) { continue; } Object o = source.getSource(); if (o instanceof Map) { for (Map.Entry<String, Object> entry : ((Map<String, Object>) o).entrySet()) { String key = entry.getKey(); m.put(key, standardServletEnvironment.getProperty(key)); } } map.put(name, m); } return R.success(map); }
3.使用PropertiesLoaderUtils獲取
感謝那些誇獎和鼓勵,那些不經意的惦記和突如其來的善意。public class PropertiesListenerConfig { public static Map<String, String> propertiesMap = new HashMap<>(); private static void processProperties(Properties props) throws BeansException { propertiesMap = new HashMap<String, String>(); for (Object key : props.keySet()) { String keyStr = key.toString(); try { // PropertiesLoaderUtils的預設編碼是ISO-8859-1,在這裡轉碼一下 propertiesMap.put(keyStr, new String(props.getProperty(keyStr).getBytes("ISO-8859-1"), "utf-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (java.lang.Exception e) { e.printStackTrace(); } } } public static void loadAllProperties(String propertyFileName) { try { Properties properties = PropertiesLoaderUtils.loadAllProperties(propertyFileName); processProperties(properties); } catch (IOException e) { e.printStackTrace(); } } public static String getProperty(String name) { return propertiesMap.get(name).toString(); } public static Map<String, String> getAllProperty() { return propertiesMap; } }