使用配置文件动态获取WebService地址
请看MyService.java中片段代码(由wsimport工具自动生成,请参看我的上一篇博文:使用命令wsimport构建WebService客户端):
View Code
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
View Code
1 import java.util.Properties;
2 import 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){
12 e.printStackTrace();
13 }
14 site = p.getProperty("webservice_site");
15 return site;
16 }
17 }
新建配置文件general.properties
View Code
1 webservice_site = http://localhost:8080/Demo/services/MyService
修改MyService.java
View Code
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
View Code
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 }
如有疑问请参看我前几篇博文,也可以去http://www.cnblogs.com/likehua/archive/2011/08/16/2141540.html看看!