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;
}
}
