一、添加Maven依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version> 2.9.2</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version> 1.9.6</version>
</dependency>
二、添加配置类
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
// 启用 Swagger2
@EnableSwagger2
public class Swagger2 {
//是否开启swagger
@Value("${swagger2.enable:false}")
private boolean swagger2Enable;
//网关地址 不走网关可以注释
//@Value("${swagger2.gateway-url}")
//private String swagger2GateWay;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(swagger2Enable)
.apiInfo(apiInfo())
//.host(swagger2GateWay)
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// 标题
.title("****服务接口")
// Api 文档描述
.description("****服务API")
// 文档作者信息
.contact(new Contact("xx", "xx", "xxx"))
// 文档版本
.version("1.0")
.build();
}
}
三、配置文件 (也可以不用)
swagger2:
enable: true
gateway-url: localhost:18000
四、启动项目
启动项目成功后访问:http://ip:port/doc.html
五、常用注解
Controller
@RestController
@RequestMapping(name = "名称", value = "/路由/")
@Api(tags = {"测试swagger Api 接口文档"})
public class TestController {
@Autowired
private TestService testService;
@ApiOperation(value = "测试1接口 查询接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "starDate", value = "开始时间", required = false, paramType = "query"),
@ApiImplicitParam(name = "endDate", value = "结束时间", required = false, paramType = "query")
})
@RequestMapping(name = "测试1接口 查询接口", value = "get.json", method = RequestMethod.GET)
public Object get(String starDate,String endDate){
return testService.get(starDate,endDate);
}
}
Bean
/**
* 开始时间
*/
@ApiModelProperty(value = "开始时间")
private String starDate;