Java读取properties配置有两个方式:
- 在SpringBoot项目中,可以通过spring的注解读取配置
- 不通过spring注解读取配置
1. 通过spring的注解读取配置,其有三种方法:
1.1 @Value
@Value("${spring.profiles.active}")
private String profileActive;
# 相当于把properties文件中的spring.profiles.active注入到变量profileActive中
1.2 @ConfigurationProperties
@Component
@ConfigurationProperties(locations = "classpath:application.properties",prefix="test")
public class TestProperties {
String url;
String key;
}
其他类中使用时,就可以直接注入该TestProperties 进行访问相关的值
注:@ConfigurationProperties也可用于其他.properties文件,只要locations指定即可
1.3 使用Enviroment
private Enviroment env;
env.getProperty("test.url");
env方式效率较低
2. 不通过spring注解读取配置
package com.zetyun.pccc.monitorcenter.util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
/**
* Created by lumk on 17-6-5.
*/
public class PropertiesUtils {
/**
* 获得值
*
* @param key 键
* @return 值
*/
public static String getConfigValue(String key) {
Properties p;
p = new Properties();
FileInputStream fis = null;
URL url;
url = PropertiesUtils.class.getClassLoader().getResource("application.properties");
try {
fis = new FileInputStream(url.getPath());
p.load(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return p.getProperty(key);
}
}