springboot
springboot下,请直接使用@Value读取配置文件。举个栗子:
@Value("${session.timeout:5000}")
另外:如果对静态变量赋值,有以下两种方法
//1. 通过@PostConstruct注解
@Component
public class Example {
@Autowired
private Environment environment;
public static String value1;
@PostConstruct
public void init(){
value1 = environment.getProperty("spring.value1");
}
}
//2. 通过set方法
@Component
public class Example {
private static String value2;
@Value("${spring.value2}")
public void setValue2(String value) {
Example.value2 = value;
}
自定义工具类
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 配置文件工具类
* @author 019530
* @date 2020-07-08
*/
public class PropertiesUtils {
private static String filename = "application.properties";
private static Properties properties = null;
static {
if(null == properties){
properties = new Properties();
InputStream is = null;
try{
is = PropertiesUtils.class.getClassLoader().getResourceAsStream(filename);
properties.load(is);
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if(is != null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 获取配置文件
* @param key
* @return
*/
public static String getString(String key){
return properties.getProperty(key);
}
/**
* 获取配置文件,并设置默认值
* @param key
* @param defaultValue
* @return
*/
public static String getProperty(String key, String defaultValue) {
return properties.getProperty(key, defaultValue);
}
}