基于HTTP的Webservice相比于基于SOAP协议的Webservice一大缺点就是缺少约束和文档定义,因此我们需要采用Swagger完成对接口的定义,以及相关代码生成等。
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
@EnableDiscoveryClient
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
package com.example.demo.controller;
import com.example.demo.*;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/foos")
@Api("Foo CRUD服务")
public class FooController {
@Autowired
private FooService fooService;
@GetMapping("/all")
@ApiOperation("根据条件不分页查询结果")
public List<FooDto> findAll(FooQo fooQo) {
return fooService.findAll(fooQo);
}
@GetMapping("/{id}")
@ApiOperation("根据ID查询结果")
public FooDto findById(@ApiParam("业务主键") @PathVariable("id") Long id) {
Optional<FooDto> optional = fooService.findById(id);
if (optional.isPresent()) {
return optional.get();
} else {
throw new ResourceNotFoundException("Foo", id);
}
}
}
package com.example.demo.dto;
import com.taocares.commons.beans.annotation.Mapping;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@ApiModel("Foo数据传输对象")
public class FooDto {
@ApiModelProperty(value = "唯一标识", example = "1")
private Long id;
@ApiModelProperty(value = "名字", example = "张三")
private String name;
@ApiModelProperty(value = "时间", example = "2018-10-01")
@Mapping(datePattern = "yyyy-MM-dd")
private String date;
}