学习网站建设0学起,pc网站设计哪家公司好,设计在线中国,安全的营销型网站制作需求#xff1a;在学习FC时#xff0c;启动一个springboot项目时需要由用户填写自己的某些特殊变量#xff0c;解决方案是在FC中由用户自己添加环境变量#xff0c;通过java代码获取到环境中的环境变量#xff0c;在springboot启动前注入到yaml文件中。
1.java获取环境变…需求在学习FC时启动一个springboot项目时需要由用户填写自己的某些特殊变量解决方案是在FC中由用户自己添加环境变量通过java代码获取到环境中的环境变量在springboot启动前注入到yaml文件中。
1.java获取环境变量
环境变量环境变量Environment Variables是计算机操作系统中存储一些动态值的变量这些值可以影响运行中的进程和程序的行为。环境变量通常以键-值对的形式存在并可以在操作系统的命令行界面或者代码中进行设置和访问。 java提供了两种获取环境变量的方法。
System.getenv()System.getProperty() 我们在这篇文章中使用的是第一种方法。
public static String getEnv(){MapString, String env System.getenv();return env.get(biz);}System.getenv()获取到所有环境变量的键值对。 env.get(“biz”)获取到keybiz的环境变量。在这里是一个json列表的String所以我们需要将这个String转为json
2.将String转为Json对象
public static JSONObject getJsonObject(String str){return JSON.parseObject(str);}使用阿里的两个处理Json的包。
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;3.修改yaml文件并注入到项目中
在springboot项目启动前获取到环境变量写入到yml文件中的配置的变量。 这样启动的springboot项目就可以获取到不同的环境变量。 需要SnakeYAML的能力所以需要再Maven中添加SnakeYAML的依赖
dependencygroupIdorg.yaml/groupIdartifactIdsnakeyaml/artifactIdversion1.29/version
/dependency
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;public class YamlModifier {public static void main(String[] args) {String filePath application.yml;try {// 读取YAML文件FileInputStream inputStream new FileInputStream(filePath);Yaml yaml new Yaml();MapString, Object data yaml.load(inputStream);// 修改YAML文件内容modifyYml(data);// 写回YAML文件writeYml(data, filePath);} catch (IOException e) {e.printStackTrace();}}private static void modifyYml(MapString, Object data) {// 修改YAML文件中的某个值例如修改数据库配置MapString, Object spring (MapString, Object) data.get(spring);if (spring ! null) {MapString, Object datasource (MapString, Object) spring.get(datasource);if (datasource ! null) {datasource.put(url, jdbc:mysql://newhost:3306/newdb);datasource.put(username, newuser);datasource.put(password, newpassword);}}}private static void writeYml(MapString, Object data, String filePath) throws IOException {// 将修改后的Map写回YAML文件DumperOptions options new DumperOptions();options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);Yaml yaml new Yaml(options);try (FileWriter writer new FileWriter(filePath)) {yaml.dump(data, writer);}}
}