java 如何发布webservice
使用 JAX-WS 发布 WebService
JAX-WS 是 Java 提供的标准 API,用于开发和发布 WebService。以下是具体实现步骤:
-
创建服务接口和实现类
定义一个服务接口,使用@WebService注解标记:@WebService public interface HelloService { String sayHello(String name); }实现该接口:
@WebService(endpointInterface = "com.example.HelloService") public class HelloServiceImpl implements HelloService { @Override public String sayHello(String name) { return "Hello, " + name; } } -
发布服务
使用Endpoint类发布服务:public class WebServicePublisher { public static void main(String[] args) { String url = "http://localhost:8080/hello"; Endpoint.publish(url, new HelloServiceImpl()); System.out.println("WebService 发布成功,访问地址: " + url); } } -
访问 WSDL
服务发布后,通过浏览器访问http://localhost:8080/hello?wsdl查看 WSDL 文件。
使用 Spring Boot 发布 WebService
Spring Boot 集成 Apache CXF 可以简化 WebService 的发布:

-
添加依赖
在pom.xml中添加以下依赖:<dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-spring-boot-starter-jaxws</artifactId> <version>3.5.5</version> </dependency> -
定义服务接口和实现类
使用@WebService注解标记接口和实现类:@WebService public interface GreetingService { String greet(String name); } @WebService(endpointInterface = "com.example.GreetingService") public class GreetingServiceImpl implements GreetingService { @Override public String greet(String name) { return "Greetings, " + name; } } -
配置 CXF 端点
创建配置类注册服务:@Configuration public class WebServiceConfig { @Autowired private Bus bus; @Bean public Endpoint endpoint() { Endpoint endpoint = new EndpointImpl(bus, new GreetingServiceImpl()); endpoint.publish("/greeting"); return endpoint; } } -
启动服务
启动 Spring Boot 应用后,访问http://localhost:8080/services/greeting?wsdl查看 WSDL。
使用 JAX-RS 发布 RESTful WebService
如果需要发布 RESTful 风格的 WebService,可以使用 JAX-RS:
-
添加依赖
对于 Spring Boot,添加以下依赖:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> -
定义 REST 端点
使用@RestController和@RequestMapping注解:@RestController @RequestMapping("/api") public class RestService { @GetMapping("/hello") public String sayHello(@RequestParam String name) { return "Hello, " + name; } } -
启动服务
启动 Spring Boot 应用后,通过http://localhost:8080/api/hello?name=World访问服务。
注意事项
- 端口冲突:确保发布的端口未被占用。
- WSDL 访问:服务发布后,必须通过
?wsdl后缀访问 WSDL。 - 安全性:生产环境建议添加安全措施(如 HTTPS、认证)。
- 日志:使用 CXF 或 JAX-WS 时,可以配置日志拦截器查看 SOAP 消息。
以上方法覆盖了从传统 SOAP 到现代 RESTful 的 WebService 发布需求。






