版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wu_zi/article/details/79565084
步骤:
1、添加pom依赖
<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>
2、初始化配置
在与SpringBootApplication同级别的目录下添加配置文件。
package com.zzh;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.spring.web.plugins.Docket;
import org.springframework.context.annotation.Bean;
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.swagger2.annotations.EnableSwagger2;
/**
* Created by minhu on 18/3/15.
*/
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.zzh.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springboot利用swagger构建api文档")
.description("简单优雅的restfun风格,http://blog.csdn.net/wu_zi")
.termsOfServiceUrl("http://blog.csdn.net/wu_zi")
.version("1.0")
.build();
}
}
apis(RequestHandlerSelectors.basePackage("com.zzh.controller"))这里设置的包名是你的controller的包名
3、在controller文件中添加对应的注解
package com.zzh.controller;
import com.zzh.properties.GirlProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@Api(description = "hello world I'm coming")
@RestController
@RequestMapping("/hello")
public class HelloController {
@Autowired
private GirlProperties girlProperties;
@ApiOperation(value = "简单的输入什么id就输出什么", notes = "没什么啦……", httpMethod = "GET")
@RequestMapping(value = "/{id}/say", method = RequestMethod.GET)
public String say(@PathVariable("id") Integer myId) {
return "id: " + myId;
}
@ApiOperation(value = "直接输出id,默认值是0", notes = "没什么啦……", httpMethod = "GET")
@RequestMapping(value = "/talk", method = RequestMethod.GET) //等同于@GetMapping(value="/talk")
public String talk(@RequestParam(value = "id", required = false, defaultValue = "0") Integer myId) {
return "id: " + myId;
}
}
效果图:
另外今天在学习使用SpringBoot配置swagger文档遇到一个问题,记录一下。
问题如上图所示,Unable to inger base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway. The base url is the root of.....
产生的原因是:在配置swagger的时候没有加上注解
解决的话,直接加上@Configuration和@EnableSwagger2两个注解就好了。