- 使用ClassLoader加载properties配置文件生成对应的输入流
public static String getProperties(String key) throws Exception {
Properties properties = new Properties();
// 使用ClassLoader加载properties配置文件生成对应的输入流
InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream("application.properties");
// 使用properties对象加载输入流
properties.load(in);
//获取key对应的value值
return properties.getProperty(key);
}
- ResourceBundle
public static String getProperties(String key) throws Exception {
//config为属性文件名,放在包com.test.config下,如果是放在src下,直接用config即可
ResourceBundle resource = ResourceBundle.getBundle("application");
return resource.getString(key);
}
- 使用InPutStream流读取properties文件
public static String getProperties(String key) throws Exception {
Properties properties = new Properties();
// 使用InPutStream流读取properties文件
BufferedReader bufferedReader = new BufferedReader(new FileReader("E:/config.properties"));
properties.load(bufferedReader);
// 获取key对应的value值
return properties.getProperty(key);
}
Spring支持文件读取方式
public static String getProperties(String key) throws Exception{
Resource resource = new ClassPathResource("application.properties");
Properties prop = PropertiesLoaderUtils.loadProperties(resource);
return prop.getProperty(key);
}
- @Value注解
@Value(${"logging.path"})
private String logPath;
网友评论