技術交流羣:233513714html
1、建立maven工程引入依賴git
<dependencies> <!----------swagge依賴-----------> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency> <!----------jackson依賴-----------> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.7</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jsckson-annotions</artifactId> <version>2.9.7</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.7</version> </dependency> </dependencies>
2、Swagger2配置github
@Configuration //SpringBoot配置註解 @EnableSwagger2 //啓用Swagger2功能註解 public class SwaggerConfig { @Bean public Docket createRestfulApi() {//api文檔實例 return new Docket(DocumentationType.SWAGGER_2)//文檔類型:DocumentationType.SWAGGER_2 .apiInfo(apiInfo())//api信息 .select()//構建api選擇器 .apis(RequestHandlerSelectors.basePackage("com.datad.dream.controller"))//api選擇器選擇api的包 .paths(PathSelectors.any())//api選擇器選擇包路徑下任何api顯示在文檔中 .build();//建立文檔 } private ApiInfo apiInfo() {//接口的相關信息 return new ApiInfoBuilder() .title("SpringBoot使用Swagger2構建RESTful接口") .description("Swagger接口文檔路徑爲:http://localhost:8080/swagger-ui.html") .termsOfServiceUrl("http://localhost:8080/swagger-ui.html")
.contact("sunf")
.version("1.0")
.license("http://springfox.github.io/springfox/docs/current/")
.licenseUrl("http://springfox.github.io/springfox/docs/current/")
.build();
}
}
3、Swagger2註解使@RestController //接口註解@Api(value="用戶接口",tags={"catTest"}) //接口簡要標註,對中文的支持不太好spring
@RequestMapping(value = "/swagger") //接口基本路徑 public class AnimalController { //接口須要的參數,能夠有多個,這裏只寫了一個,它的paramType還有path、query、body、form幾種, @ApiImplicitParams({ @ApiImplicitParam(paramType = "header", name = "Token", value = "token", dataType = "String", required = true,defaultValue = "123")}) //接口功能描述 @ApiOperation(value = "獲取一隻貓") //接口響應信息,這裏定義了一個401,當出現401,接口返回的是自定的錯誤AnimalError的實例。固然能夠定義多個。 @ApiResponses(value = { @ApiResponse(code = 401, message = "請求未經過認證.", response = AnimalError.class) }) @RequestMapping(value="/onecat", method = RequestMethod.GET) public Cat oneCat(){ Cat cat = new Cat(); cat.setAge("1"); cat.setBreed("波斯貓"); cat.setName("Tom"); return cat; } } @Getter @Setter @ToString @ApiModel(description = "貓咪實體類") public class Cat{ @ApiModeProperty(value = "年齡") private String age; @ApiModeProperty(value = "品種") private String breed; @ApiModeProperty(value = "名字") private String name; }
4、查看接口信息api
一、在瀏覽器輸入網址http://localhost:8080/swagger-ui.html瀏覽器
二、展開接口列表app
三、進入接口maven
四、調用成功後返回ui