1.导包
<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>
2.配置
package com.example.boot.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.core.env.Environment; import org.springframework.core.env.Profiles; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; 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; import java.util.ArrayList; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket docket(Environment environment){ Profiles profiles = Profiles.of("dev","test");//若配置文件存在则访问http://localhost:8081/swagger-ui.html启动渲染 //获取项目的环境 boolean flag = environment.acceptsProfiles(profiles); System.err.println(flag); return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .enable(flag)//取消使用 .select() //RequestHandlerSelectors扫描接口方式 //basePackage扫包 //any()扫描全部 //none()不扫描 //withClassAnnotation扫描类上注解 //withMethodAnnotation扫描方法上的注解 .apis(RequestHandlerSelectors.withMethodAnnotation(GetMapping.class))//指定包 //.paths(PathSelectors.ant("/user/**")) .build(); } //配置swagger信息=apiInfo private ApiInfo apiInfo(){ Contact contact = new Contact("ariel", "http://localhost:8080", "ab842618233@qq.com"); return new ApiInfo("Api Swagger", "Apixxx", "1.0", "http://localhost:8080", contact, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList()); } }
3.分组
public Docket docket(Environment environment){//依次定义多个方法就可以得.apiInfo(apiInfo()).groupName("namexxx")定义多个组名
4.注解
@ApiModel标识实体类
@ApiModelProperty字段
@ApiOperation标识方法
@ApiParam标识参数
好处:1.接口文档实时更新,2.给较难理解的属性或者接口注释,3.可以在线测试