先圖片後代碼html
第一步:在pom.xml文件上添加Swagger依賴前端
<!--Swagger API獲取的包--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.8.0</version> </dependency> <!--Swagger 官方給出的一個ui界面,這個界面能夠自定義,默認是官方的--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.8.0</version> </dependency> <!--Swagger 測試數據以JSON格式返回的依賴包--> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.9.13</version> </dependency>
第二步:配置Swaggerjava
新建Swagger配置類,特別注意圖片標紅的地方是掃描你接口的包名,這是掃描註解的配置,即你的API接口位置,對前端提供服務接口的位置。spring
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi() {// 建立API基本信息 List<springfox.documentation.service.Parameter> pars = new ArrayList<>(); ParameterBuilder ticketPar = new ParameterBuilder(); ticketPar.name("token").description("user token") .modelRef(new ModelRef("string")).parameterType("header") .required(false).build(); //header中的token參數非必填,傳空也能夠 pars.add(ticketPar.build()); //根據每一個方法名也知道當前方法在設置 // ticketPar = new ParameterBuilder(); ticketPar.name("source").description("user source ") .modelRef(new ModelRef("string")).parameterType("header") .required(false).build(); //header中的source參數非必填,傳空也能夠 pars.add(ticketPar.build()); //根據每一個方法名也知道當前方法在設置 return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.aaa.controller"))// 掃描該包下的全部須要在Swagger中展現的API,@ApiIgnore註解標註的除外 .paths(PathSelectors.any()) .build().globalOperationParameters(pars); } private ApiInfo apiInfo() {// 建立API的基本信息,這些信息會在Swagger UI中進行顯示 return new ApiInfoBuilder() .title("開發接口API文檔")// API 標題 .description("<h4>更新日誌</h4>")// API描述 .contact("ZHL")// 聯繫人 .version("v1.0")// 版本號 .build(); } }
第三步:編輯Controller層json
@RestController @Api(value = "登陸控制器") public class LoginController { @GetMapping("/test") @ApiOperation(value = "查詢班級", notes = "根據名稱查詢班級中的學生") @ApiImplicitParams({ @ApiImplicitParam(paramType = "query", name = "name", value = "學生名1", required = true, dataType = "String", example = "大朱"), @ApiImplicitParam(paramType = "query", name = "name2", value = "學生名2", required = true, dataType = "String", example = "小朱"), @ApiImplicitParam(paramType = "query", name = "name3", value = "學生名3", required = true, dataType = "String", example = "小熊") }) public Object queryS(String name, String name2, String name3) { return null; } }
第四步:在application.yml添加Swagger的path(json的訪問request mapping.能夠自定義,防止與自身代碼衝突)api
API doc的顯示路由是:http://localhost:8081/swagger-ui.html 這是我本身的端口app
springfox: documentation: swagger: v2: path: /api-docs
第五步:啓動Springboot查看效果測試
http://localhost:8081/swagger-ui.htmlui