已有 WebService 實作類(如 FileMarkService),需快速生成標準 WSDL 提供給消費方或文檔化。
Java2WSDLimport org.apache.cxf.tools.java2ws.JavaToWS;
import net.bwda.service.Busi.webservice.FileMarkService;
public class Java2WSDL {
private Class<?> className;
private String[] args1, args2, args3;
/** 僅指定服務類 */
public Java2WSDL(Class<?> className) {
this.className = className;
// 1. 生成到 ./resource 目錄
args1 = new String[]{"-wsdl", "-d", "./resource", this.className.getName()};
// 2. 生成到 ./example 目錄
args2 = new String[]{"-wsdl", "-cp", "./example", this.className.getName()};
// 3. 自訂檔名輸出到當前目錄
args3 = new String[]{"-o", "myHello.wsdl", "-wsdl", this.className.getName()};
}
/** 指定服務類與輸出檔名 */
public Java2WSDL(Class<?> className, String wsdlFileName) {
this.className = className;
args1 = new String[]{"-wsdl", "-d", "./resource", this.className.getName()};
args2 = new String[]{"-wsdl", "-cp", "./example", this.className.getName()};
args3 = new String[]{"-o", wsdlFileName + ".wsdl", "-wsdl", this.className.getName()};
}
public void java2WSDL(String[] args) {
JavaToWS javaToWS = new JavaToWS(args);
try { javaToWS.run(); }
catch (Exception e) { e.printStackTrace(); }
}
public static void main(String[] args) {
Java2WSDL generator = new Java2WSDL(FileMarkService.class);
generator.java2WSDL(generator.args1); // 使用方案 1
}
}
| 參數 | 含義 |
|---|---|
-wsdl | 生成 WSDL 模式 |
-d <dir> | 輸出目錄 |
-cp <path> | 類路徑(用於載入服務類) |
-o <file> | 指定輸出檔名 |
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-tools-java2ws</artifactId>
<version>3.1.12</version> <!-- 對應 CXF 版本 -->
</dependency>
<plugin>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-java2ws-plugin</artifactId>
<version>${cxf.version}</version>
<executions>
<execution>
<id>generate-wsdl</id>
<phase>process-classes</phase>
<configuration>
<className>net.bwda.service.Busi.webservice.FileMarkService</className>
<outputFile>${project.build.directory}/wsdl/FileMarkService.wsdl</outputFile>
<frontend>jaxws</frontend>
<databinding>jaxb</databinding>
</configuration>
<goals>
<goal>java2ws</goal>
</goals>
</execution>
</executions>
</plugin>
執行 mvn process-classes 即可在編譯階段自動產出 WSDL,適合 CI/CD 流水線。
-cp 包含編譯後的 target/classes 或打包後的 JAR@XmlRootElement 等註解@WebService 介面,需指定 -sn (serviceName) 區分CXF JavaToWS 提供程式化與 Maven Plugin 兩種生成 WSDL 方式,滿足開發期快速驗證與構建期自動化雙重需求。掌握核心參數,即可靈活整合至專案工作流。