1.Spring读取properties配置
@Component
@Configurable
@EnableScheduling
@PropertySource({"classpath:config/camera.properties"})
public class BackgroundTaskService {
@Value("${camera1.saveInterval}")
private int saveInterval;
// 每隔指定毫秒运行一次,上一次必须先完成
@Scheduled(fixedDelayString = "${camera1.saveInterval}")
public void reportCurrentTime(){}
}
2.java原生获取配置文件信息
package com.kenick.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Properties;
/**
* Created by kenick on 2018/11/14.
*/
public class PropertiesUtil {
private final static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
private Properties props;
private String projectPath;
public PropertiesUtil(){
projectPath = new File(this.getClass().getResource("/").getPath()).getPath();
}
public void loadProperties(String filePath){
props = new Properties();
try {
InputStream is = new FileInputStream(filePath);
props.load(new InputStreamReader(is,"UTF-8"));
} catch (IOException e) {
logger.error("配置文件读取异常",e);
}
}
public String getProperty(String key){
return props.getProperty(key.trim()).trim();
}
public String getProperty(String key,String defaultValue){
String value= props.getProperty(key.trim());
if (value == null || "".equals(value)){
value = defaultValue;
}
return value.trim();
}
public String getProjectPath(){
return projectPath;
}
public static void main(String[] args) {
PropertiesUtil propertiesUtil = new PropertiesUtil();
String filePath = propertiesUtil.getProjectPath() + "/config/camera.properties";
propertiesUtil.loadProperties(filePath);
String ip = propertiesUtil.getProperty("camera1.ip");
System.out.println(ip);
}
}
3.两者区别:spring在启动时加载一次配置文件,导致后续修改配置文件,将不会再生效;原生为每次运行都从文件中获取信息,所以可以达到实时生效,不过会占用更多的IO资源。