工作中会遇到一些 小需求,不需要项目一直持续提供功能,却需要每天定时触发一次,这种任务,只要常规 jar 包 + 定时调度就可以处理了。针对这种项目,一些敏感信息,比如,appKey 等信息,因为可能会变化,又不经常修改的,可以放置到配置文件中,从外部加载
获取路径
- 获取 jar 包运行路径
// System.getProperty("user.dir") 获取当前 jar 包运行路径
String jarPath = System.getProperty("user.dir");
解析文件内容
- 手动解析
- 使用 SpringBoot 框架来解析
手动解析
try {
final InputStream inputStream = new File(configPath).toURI().toURL().openStream();
final Properties properties = new Properties();
properties.load(inputStream);
inputStream.close();
log.info("properties-size: {}", properties.size());
return properties;
} catch (IOException e) {
log.error("读取配置文件异常: path:{}, errorMessage:{}, e:{}", configPath, e.getMessage(), e);
System.exit(-1);
}
使用 SpringBoot 框架来解析
- 该方式需要使用 springboot 框架
- 外部配置文件必须是 properties 类型,不能是 yaml 类型
- 该方式是运行时获取运行路径,然后将配置文件路径设置在系统变量里,交给 spring 的 PropertySource 去解析
设置解析路径
public static void main(String[] args) {
// 加配置用以解析 指定的配置文件
final String chenfu = String.format("%s%s%s%s%s", System.getProperty("user.dir"), File.separator, "config", File.separator, "chenfu.properties");
System.setProperty("chenfu", chenfu);
new SpringApplicationBuilder(ChenfuApplication.class).web(WebApplicationType.NONE).run(args);
}
解析参数配置类
@Component
@ConfigurationProperties(prefix = "chenfu", ignoreInvalidFields = true)
@PropertySource(value = "file:${chenfu}", encoding = "UTF-8")
public class ChenfuApplication {
// 配置项
}