使用配置檔案動態獲取WebService地址
阿新 • • 發佈:2019-02-07
請看MyService.java中片段程式碼(由wsimport工具自動生成)
1 static {
2 URL url = null;
3 WebServiceException e = null;
4 try {
5 url = new URL("http://localhost:8080/Demo/services/MyService?wsdl"); //硬編碼 6 } catch (MalformedURLException ex) {
7 e = new WebServiceException(ex);
8}
9 MYSERVICE_WSDL_LOCATION = url;
10 MYSERVICE_EXCEPTION = e;
11 }
如果程式中"http://localhost:8080/Demo/services/MyService?wsdl"標紅部分發生改變,是否需要我們使用wsimport工具重新生成客戶端呢?答案當然是不允許,也是不行的,你懂的。
解決方法:地址通過讀取配置檔案來獲得,地址如果發生變動,只需要修改配置檔案,程式無需修改!
新建檔案PropertiesConfig.java
1 import java.util.Properties;
2import java.io.FileInputStream;
3 public class PropertiesConfig {
4
5 public static String site;
6
7 public static String getSite(){
8 Properties p = new Properties();
9 try{
10 p.load(new FileInputStream("src/general.properties"));
11 }catch(Exception e){
12e.printStackTrace();
13 }
14 site = p.getProperty("webservice_site");
15 return site;
16 }
17 }
新建配置檔案general.properties
1 webservice_site = http://localhost:8080/Demo/services/MyService
修改MyService.java
1 static {
2 URL url = null;
3 String str = PropertiesConfig.getSite();//新增 4 WebServiceException e = null;
5 try {
6 url = new URL(str+"?wsdl");//修改 7 } catch (MalformedURLException ex) {
8 e = new WebServiceException(ex);
9 }
10 MYSERVICE_WSDL_LOCATION = url;
11 MYSERVICE_EXCEPTION = e;
12 }
測試Test.java
1 public class Test {
2
3 /** 4 * @param args
5 */
6 public static void main(String[] args) {
7 // TODO Auto-generated method stub 8 MyService server = new MyService();
9 MyServicePortType spt = server.getMyServiceHttpPort();
10 System.out.println(spt.example("hello"));
11 }
12
13 }