1、classload().getResourceAsStream(“name”) :从classPath下获取
Properties properties = new Properties();
InputStream is = demo.class.getClassLoader().getResourceAsStream("database.properties");
try {
System.out.println(is);
properties.load(is);
} catch (Exception e) {
throw new IOException("config loading fail"+e);
}
String usernmae = properties.getProperty("username");
2、ResourceBundle.getBundle(“configname”) :必须是properties文件,必须在classpath目录下
ResourceBundle resourceBundle = ResourceBundle.getBundle("database");
Enumeration<String> keys = resourceBundle.getKeys();
while(keys.hasMoreElements()){
String key = keys.nextElement();
String value = resourceBundle.getString(key);
System.out.println(key+" : "+value);
如果是CN环境,使用ResourceBundle类,读取的是database_zh_CN.properties和database.properties和并集。如果两个配置文件都有一个属性,database_zh_CN.properties中的属性会覆盖database.properties配置文件中的属性。
**3、使用Spring自带的PropertiesLoaderUtils工具类 :**加载classpath目录下,yml和properties格式都可以
Properties pro = null;
pro = PropertiesLoaderUtils.loadAllProperties("application-dev.yml");
Enumeration<?> enumeration = pro.propertyNames();
/**
遍历打印properties文件中key集合
*/
while(enumeration.hasMoreElements()){
String name = (String)enumeration.nextElement();
String value = pro.getProperty(name);
System.out.println(name+" : "+value);
}
4、Environment获取配置文件:
package com.laty.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@SpringBootApplication
@RestController
@ComponentScan("com.laty")
public class TestController {
@Autowired
Environment env;
@RequestMapping("/value")
public Map<String,String> get(){
HashMap map = new HashMap();
map.put("url",env.getProperty("spring.datasource.url"));
return map;
}
public static void main(String[] args) {
SpringApplication.run(TestController.class,args);
}
}