SpringBoot配置Swagger2
添加依賴
pom.xml
<!-- Swagger2 Begin -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!-- Swagger2 End -->
配置 Swagger2
注意:RequestHandlerSelectors.basePackage("com.demon.service")
為 Controller 包路徑,不然生成的文檔掃描不到接
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
public class Swagger2Configuration {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.demon.service"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Demon API 文檔")
.description("Demon API 網(wǎng)關(guān)接口")
.version("1.0.0")
.build();
}
}
啟用 Swagger2
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
public class LoginApplication {
public static void main(String[] args) {
SpringApplication.run(LoginApplication.class,args);
}
}
Swagger 常用注解說明
Swagger 通過注解表明該接口會(huì)生成文檔利耍,包括接口名、請(qǐng)求方法盔粹、參數(shù)隘梨、返回信息的等等。
- @Api:修飾整個(gè)類舷嗡,描述 Controller 的作用
- @ApiOperation:描述一個(gè)類的一個(gè)方法轴猎,或者說一個(gè)接口
- @ApiParam:單個(gè)參數(shù)描述
- @ApiModel:用對(duì)象來接收參數(shù)
- @ApiProperty:用對(duì)象接收參數(shù)時(shí),描述對(duì)象的一個(gè)字段
- @ApiResponse:HTTP 響應(yīng)其中 1 個(gè)描述
- @ApiResponses:HTTP 響應(yīng)整體描述
- @ApiIgnore:使用該注解忽略這個(gè)API
- @ApiError:發(fā)生錯(cuò)誤返回的信息
- @ApiImplicitParam:一個(gè)請(qǐng)求參數(shù)
- @ApiImplicitParams:多個(gè)請(qǐng)求參數(shù)
訪問 Swagger2
訪問地址:http://ip:port/swagger-ui.html