swagger2 可以同步api和文檔,在開發的過程中 就省略了需要寫開發文檔以及團隊之間不必要的交接問題 自己開發過程中 其實也是比較方便測試和瀏覽api功能的 因為要寫一個用戶中心的測試 正好就用一下swagger2 配置也是比較簡單的 也會有一些小的問題 記錄一下配置過程和解決辦法
- 引入swagger2的依賴
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
- 新建swagger2 配置類 內容如下
@Configuration
@EnableSwagger2
public class Swagger2 {
/**
* @Description:swagger2的配置文件,這里可以配置swagger2的一些基本的內容,比如掃描的包等等
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.emp.usercenter.pc"))
/* .apis(RequestHandlerSelectors.withClassAnnotation(Controller.class))*/
.paths(PathSelectors.any())
.build();
}
/**
* @Description: 構建 api文檔的信息
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// 設置頁面標題
.title("用戶中心后端api接口文檔")
// 設置聯系人
.contact(new Contact("employeeeee", "https://zhouzihao.xyz", "employeeeee@sina.com"))
// 描述
.description("歡迎訪問用戶中心接口文檔,這里是描述信息")
// 定義版本號
.version("1.0").build();
}
}
我第一次用swagger2的時候 是橫向分割的 按照不同的module來建立的項目 所以所有的
controller
都放在了一個包里,而這次的項目我是按照com.emp.*.controller
的形式來搭建的 開始嘗試使用在basepackage
中這樣寫是行不通的 所以如果是要使用多個controller的包 可以給定位到它們的上級目錄 或者是統一使用一種controller
或者restcontroller
的注解,
然后通過.apis(RequestHandlerSelectors.withClassAnnotation(Controller.class))
來掃描.
- 在controller中 添加相應的api注釋
@Controller
@Api(value = "用戶信息查詢",tags = {"用戶信息的controller"})
public class CustomerController {
@Resource
private CustomerService customerService;
@ApiOperation(value = "用戶所有信息查詢",notes = "用戶信息查詢接口")
@GetMapping("index")
private String customerIndex(Model model){
List<Customer> customerList = customerService.selectAll();
model.addAttribute("customerList",customerList);
return "customer/index";
}
}
- model中給參數添加注釋 因為我是一個查詢 沒有參數 但是如果是查詢啊 刪除什么的 就需要傳參 如下
@ApiModel(value = "用戶對象",description = "用戶實體類")
public class Customer {
/*@ApiModelProperty(hidden = true)*/
private String cid;
/*@ApiModelProperty(value = "用戶名",name = "username",example = "zhou",required = true)*/
private String cname;
然后訪問 你的 localhost + swagger-ui.html
image.png