- 設(shè)置指定鍵對值的系統(tǒng)屬性
- setProperty (String prop, String value);
- 參數(shù):
- prop - 系統(tǒng)屬性的名稱。
- value - 系統(tǒng)屬性的值。
- 返回:
- 系統(tǒng)屬性以前的值,如果沒有以前的值,則返回 null。
- 拋出:
- SecurityException - 如果安全管理器存在并且其 checkPermission 方法不允許設(shè)置指定屬性。
- NullPointerException - 如果 key 或 value 為 null。
- IllegalArgumentException - 如果 key 為空。
- 注:這里的system,系統(tǒng)指的是 JRE (runtime)system,不是指 OS。
//實例
System.setProperty("Property1", "abc");
System.setProperty("Property2","def");
//這樣就把第一個參數(shù)設(shè)置成為系統(tǒng)的全局變量!可以在項目的任何一個地方 通過System.getProperty("變量");來獲得,
//System.setProperty 相當(dāng)于一個靜態(tài)變量 ,存在內(nèi)存里面!
public class SystemTest {
static {
setValue();
}
public static void setValue() {
System.setProperty("name", "張三");
System.setProperty("age", "28");
}
public static void main(String[] args) {
System.out.println(System.getProperty("name"));
System.out.println(System.getProperty("age"));
}
}
輸出:

image.png
下面是在Tomcat源碼中Bootstrap的代碼塊
static {
// Will always be non-null 將始終為非空
String userDir = System.getProperty("user.dir");
System.out.println("userDir 當(dāng)前系統(tǒng)的用戶目錄====================>>>>>>> " + userDir);
// Home first 獲取已經(jīng)存在系統(tǒng)中的地址信息 catalina.home
String home = System.getProperty(Globals.CATALINA_HOME_PROP);
System.out.println("home first ======啟動輸出為null=======>>>>>>>>> " + home);
File homeFile = null;
if (home != null) {
File f = new File(home);
try {
homeFile = f.getCanonicalFile();
} catch (IOException ioe) {
homeFile = f.getAbsoluteFile();
}
}
if (homeFile == null) {
// First fall-back. See if current directory is a bin directory
// in a normal Tomcat install
File bootstrapJar = new File(userDir, "bootstrap.jar");
if (bootstrapJar.exists()) {
File f = new File(userDir, "..");
try {
homeFile = f.getCanonicalFile();
} catch (IOException ioe) {
homeFile = f.getAbsoluteFile();
}
}
}
if (homeFile == null) {
// Second fall-back. Use current directory
File f = new File(userDir);
try {
homeFile = f.getCanonicalFile();
} catch (IOException ioe) {
homeFile = f.getAbsoluteFile();
}
}
catalinaHomeFile = homeFile;
// 設(shè)置catalina.home鍵值中的系統(tǒng)屬性,這里設(shè)置的是Tomcat在系統(tǒng)中的地址信息
System.setProperty(
Globals.CATALINA_HOME_PROP, catalinaHomeFile.getPath());
// Then base
String base = System.getProperty(Globals.CATALINA_BASE_PROP);
if (base == null) {
catalinaBaseFile = catalinaHomeFile;
} else {
File baseFile = new File(base);
try {
baseFile = baseFile.getCanonicalFile();
} catch (IOException ioe) {
baseFile = baseFile.getAbsoluteFile();
}
catalinaBaseFile = baseFile;
}
System.setProperty(
Globals.CATALINA_BASE_PROP, catalinaBaseFile.getPath());
}