spring boot 集成WebService Cxf简单实例(rest)

本文介绍如何在Spring Boot项目中集成CXF来创建RESTful服务,并通过示例代码展示了配置过程及实现JSON数据交换的具体方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

例子如下
pom文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>springboot-cxf-rest-server</groupId>
  <artifactId>springboot-cxf-rest-server</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <parent>
	    <groupId>org.springframework.boot</groupId>
	    <artifactId>spring-boot-starter-parent</artifactId>
	    <version>1.5.9.RELEASE</version>
  </parent>
  <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
	<dependency>
    	<groupId>org.apache.cxf</groupId>
    	<artifactId>cxf-spring-boot-starter-jaxrs</artifactId>
    	<version>3.1.12</version>
	</dependency>
  </dependencies>
</project>

cxf-spring-boot-starter-jaxrs为依赖
接口类
public interface CityInterface {
	@GET
	@Path("/weather/{id}")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	String getWeather(@PathParam("id")String cityID); 
}

@Produces,字面意思是生产,代表返回给客户端的是什么类型,这里返回给客户端的是JSON
@Consumes,字面意思是消费,代表可以接受的类型,这里只接受JSON格式的数据。

接口实现类
public class City implements CityInterface{

	@Override
	public String getWeather(String cityID) {
		if("1".equals(cityID)){
			System.out.println("北京");
			return "北京";
		}
		System.out.println("河北");
		return "河北";
	}

}

根据传过来的cityID返回不同数据。
启动Application(这里和配置都写在一起)
@SpringBootApplication
public class MyServer {
	@Bean(name = Bus.DEFAULT_BUS_ID)
	public SpringBus bus(){
		SpringBus bus=new SpringBus();
		return  bus;
	}
	@Bean
	public ServletRegistrationBean dispatcherServlet() {
	    return new ServletRegistrationBean(new CXFServlet(), "/ProjectManager/*");
	  }
	@Bean
	public Server server(){
		JAXRSServerFactoryBean bean=new JAXRSServerFactoryBean();
		bean.setBus(bus());
		bean.setAddress("/");
		bean.setServiceBeans(Arrays.asList(new City()));//如果有多个服务,这里可以接收List
		return bean.create();
	}
	public static void main(String[] args) {
		SpringApplication.run(MyServer.class, args);
	}
	
}
上面代码没用默认的路径/services/*,用的是自己定义/ProjectManager/*,配合@Path.实际的访问路径为:http://localhost:8080/ProjectManager/weather/{id},测试直接用soapui测试,这里不写了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jackson陈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值