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

例子如下
pom文件

  4.0.0
  springboot-cxf-rest-server
  springboot-cxf-rest-server
  0.0.1-SNAPSHOT
  
	    org.springframework.boot
	    spring-boot-starter-parent
	    1.5.9.RELEASE
  
  
        1.8
        UTF-8
  
  
	
    	org.apache.cxf
    	cxf-spring-boot-starter-jaxrs
    	3.1.12
	
  

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

你可能感兴趣的:(WebService)