Swagger

基於springboot配置swaggergit

3步走:github

1.添加座標(pom.xml)spring

<!--swagger相關maven座標-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
<!--swagger-bootstrap-ui爲了展現更好看,能夠不添加-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.7.2</version>
</dependency>

2.編寫Swagger配置類bootstrap

@Configuration
@EnableSwagger2
public class SwaggerConfig {

/** 開放接口 */
public static final String TAG_TEST = "test";
/** 認證接口 */
public static final String TAG_AUTH = "auth";
/** 管理管理**/
public static final String TAG_MANAGE="manage";

@Bean
public Docket petApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()).tags(
new Tag(TAG_TEST,"測試接口"),
new Tag(TAG_AUTH,"認證接口"),
new Tag(TAG_MANAGE,"管理接口")
)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.resttemplateclent.controller")) //指定提供接口所在的基包
.build();
}

/**
* 該套 API 說明,包含做者、簡介、版本、host、服務URL
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("RestTemplate測試 說明")
.version("1.0")
.termsOfServiceUrl("localhost:8080/demo1/")//公司官網
.build();
}

3.編寫Controllerapi

@RestController
@Api(tags = SwaggerConfig.TAG_TEST)
@RequestMapping(SwaggerConfig.TAG_TEST)
public class TestController {

private static final String URL = "http://127.0.0.1:6666/";

@Autowired
RestTemplate restTemplate;

@PostMapping("template")
@ApiOperation(value = "測試RestTemplate", notes = "RestTemplate測試")
public String testRestTemplate(){
String requestUrl = "test/getString";
String response = restTemplate.getForObject(URL + requestUrl, String.class);
return response;
}
}

另附: Swagger經常使用註解springboot

在Java類中添加Swagger的註解便可生成Swagger接口,經常使用Swagger註解以下:app

@Api:修飾整個類,描述Controller的做用maven

@ApiOperation:描述一個類的一個方法,或者說一個接口測試

@ApiParam:單個參數描述ui

@ApiModel:用對象來接收參數

@ApiModelProperty:用對象接收參數時,描述對象的一個字段

@ApiResponse:HTTP響應其中1個描述

@ApiResponses:HTTP響應總體描述

@ApiIgnore:使用該註解忽略這個API

@ApiError :發生錯誤返回的信息

@ApiImplicitParam:一個請求參數

@ApiImplicitParams:多個請求參數

相關文章
相關標籤/搜索