在java中以运行时递归更改系统属性

我有一个问题,并在java中搜索运行时更改系统属性的示例。 换句话说,我有一个独立的库,它将加载System.setProperty("javax.net.ssl.trustStore", trustStorePath) ,其中System.setProperty("javax.net.ssl.trustStore", trustStorePath)的值将根据条件而改变。 如果条件发生变化,那么我需要更改trustStorePath的值,并需要设置System Property。

但故事是我第一次设置值时,它存储值并使用它,即使我更改了trustStorePath的值并再次设置系统属性。 这种变化没有反映出来。

那么,我该怎么做呢。 以下是相同的示例代码段。

  if (getFile(keyStorePath).exists() && isChanged ) { System.setProperty("javax.net.ssl.keyStore", keyStorePath); System.setProperty("javax.net.ssl.keyStoreType", "JKS"); System.setProperty("javax.net.ssl.keyStorePassword", Pwd); }else if (getFile(testMerchantKeyStorePath).exists() ) { System.setProperty("javax.net.ssl.keyStore", testMerchantKeyStorePath); System.setProperty("javax.net.ssl.keyStoreType", "JKS"); System.setProperty("javax.net.ssl.keyStorePassword",Pwd); } 

听起来你想要使用动态信任商店。 您可以在打开任何连接之前执行此操作:

  KeyStore ts = KeyStore.getInstance("JKS"); ts.load(new FileInputStream(new File("Your_New_Trust_Store_Path")), "password".toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ts); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), null); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); // Open Connection .... etc. .... 

每次您的trustStorePath更改时都可以执行此操作。