创建基于Apache CXF的web service例子
时间: 2024-03-23 14:38:11 浏览: 146
好的,下面是一个基于Apache CXF的web service的例子:
1. 首先,创建一个Maven项目,并添加以下依赖:
```xml
<dependencies>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-spring-boot-starter-jaxws</artifactId>
<version>3.3.7</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.3.7</version>
</dependency>
</dependencies>
```
2. 创建一个接口,并定义web service的方法:
```java
@WebService
public interface GreetingService {
@WebMethod
String sayHello(String name);
}
```
3. 创建一个实现类,并实现接口中定义的方法:
```java
@Service
@WebService(endpointInterface = "com.example.demo.GreetingService")
public class GreetingServiceImpl implements GreetingService {
@Override
public String sayHello(String name) {
return "Hello, " + name + "!";
}
}
```
4. 在配置文件中配置CXF:
```yaml
cxf:
servlet:
load-on-startup: 1
url-pattern: /services/*
jaxws:
properties:
javax.xml.ws.wsdl.service: GreetingService
javax.xml.ws.wsdl.port: GreetingServicePort
```
5. 部署应用程序并启动服务器,访问以下URL即可访问web service:
```
http://localhost:8080/services/GreetingService?wsdl
```
6. 测试web service:
```java
public class Client {
public static void main(String[] args) {
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setServiceClass(GreetingService.class);
factory.setAddress("http://localhost:8080/services/GreetingService");
GreetingService client = (GreetingService) factory.create();
String result = client.sayHello("World");
System.out.println(result);
}
}
```
以上就是一个简单的基于Apache CXF的web service例子。
阅读全文