例子如下
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测试,这里不写了