springboot " />

扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

springboot鎬庝箞璇诲彇澶栭儴鏂囦欢

扬州沐宇科技
2023-09-28 17:40:30
springboot

Spring Boot鎻愪緵浜嗗绉嶆柟寮忔潵璇诲彇澶栭儴鏂囦欢锛屼互涓嬫槸鍏朵腑鍑犵甯哥敤鐨勬柟寮忥細

  1. 浣跨敤@Value娉ㄨВ锛氬彲浠ョ洿鎺ュ湪浠g爜涓娇鐢?code>@Value娉ㄨВ娉ㄥ叆澶栭儴鏂囦欢鐨勫睘鎬у€笺€備緥濡傦紝鍙互鍦?code>application.properties鏂囦欢涓畾涔変竴涓睘鎬?code>my.file.path=/path/to/file.txt锛岀劧鍚庡湪浠g爜涓娇鐢?code>@Value娉ㄨВ娉ㄥ叆璇ュ睘鎬у€硷細
@Value("${my.file.path}")
private String filePath;
  1. 浣跨敤Environment鎺ュ彛锛氬彲浠ラ€氳繃Environment鎺ュ彛鏉ヨ鍙栧閮ㄦ枃浠朵腑鐨勫睘鎬у€笺€備緥濡傦紝鍙互鍦ㄤ唬鐮佷腑娉ㄥ叆Environment鎺ュ彛锛岀劧鍚庝娇鐢?code>getProperty()鏂规硶鏉ヨ幏鍙栧睘鎬у€硷細
@Autowired
private Environment env;
public void readFilePath() {
String filePath = env.getProperty("my.file.path");
}
  1. 浣跨敤@ConfigurationProperties娉ㄨВ锛氬彲浠ラ€氳繃@ConfigurationProperties娉ㄨВ灏嗗閮ㄦ枃浠朵腑鐨勫睘鎬у€肩粦瀹氬埌涓€涓狫ava Bean涓€傞鍏堬紝鍦↗ava Bean涓畾涔夊睘鎬э紝骞朵娇鐢?code>@ConfigurationProperties娉ㄨВ鎸囧畾灞炴€х殑鍓嶇紑锛岀劧鍚庡湪application.properties鏂囦欢涓畾涔変互璇ュ墠缂€寮€澶寸殑灞炴€э紝鏈€鍚庡湪浠g爜涓敞鍏ヨJava Bean鍗冲彲銆備緥濡傦細
@ConfigurationProperties(prefix = "my.file")
public class FileProperties {
private String path;
// getter and setter
}
// application.properties
my.file.path=/path/to/file.txt
// Code
@Autowired
private FileProperties fileProperties;
public void readFilePath() {
String filePath = fileProperties.getPath();
}

浠ヤ笂鏄嚑绉嶅父鐢ㄧ殑鏂瑰紡锛屾牴鎹疄闄呴渶姹傞€夋嫨閫傚悎鐨勬柟寮忔潵璇诲彇澶栭儴鏂囦欢銆?/p>

扫码添加客服微信