Springboot整合Swagger2配置
阿新 • • 發佈:2021-09-08
1、匯入依賴
<!-- Swagger API文件 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> <exclusions> <exclusion> <groupId>io.swagger</groupId> <artifactId>swagger-annotations</artifactId> </exclusion> <exclusion> <groupId>io.swagger</groupId> <artifactId>swagger-models</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>swagger-bootstrap-ui</artifactId> <version>1.9.6</version> </dependency> <!-- # 增加兩個配置解決 NumberFormatException --> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-annotations</artifactId> <version>1.5.22</version> </dependency> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-models</artifactId> <version>1.5.22</version> </dependency>
2、Swagger2Config.java的配置
@Slf4j @Configuration @EnableWebMvc @EnableSwagger2 @ComponentScan(basePackages = "com.ma.controller") public class Swagger2Config implements WebMvcConfigurer { @Bean public Docket controller_api(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo())//介面文件資訊 .select() //查詢 .apis(RequestHandlerSelectors.basePackage("com.ma.controller")) //生成文件的包 .paths(PathSelectors.any()) //路徑 .build() //構建 .groupName("控制類介面"); //組名 } @Bean public Docket domain_api(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.ma.domain")) .paths(PathSelectors.any()) .build() .groupName("實體類"); } @Bean public Docket untiy_api(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.ma.untiy")) .paths(PathSelectors.any()) .build() .groupName("工具類"); } public ApiInfo apiInfo(){ return new ApiInfoBuilder() .title("第一個介面文件")//介面文件標題 .version("v-1")//版本 .description("這是第一個介面文件測試")//介面文件描述 .license("The Apache License, Version 2.0")//執照 .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html") //執照地址 .contact(new Contact("張三","https://www.baidu.com","[email protected]")) //團隊 .build(); //構建介面文件資訊 } /** * * 顯示swagger-ui.html文件展示頁,還必須注入swagger資源: * * @param registry */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); } }
3、在需要生成文件的類上加上註解
@Api(tags = "控制類") //在介面上添加註解
@ApiOperation(value = "返回值方法")//在方法上添加註解
@ApiModelProperty(value = "id") //實體類欄位上的註解