1. 程式人生 > 實用技巧 >Springboot系列-整合swagger

Springboot系列-整合swagger

package pers.sun.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
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  
//開啟swagger public class SwaggerConfig { /** * 宣告(或者說往spring容器中註冊)一個Docket例項 * ===>所有的配置都在Docket物件中設定 */ @Bean public Docket docket(Environment environment){ //根據當前的開發環境決定是否開啟swaggerUI,配合.enable(flag) Profiles profiles=Profiles.of("dev"); boolean flag
=environment.acceptsProfiles(profiles); return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) //更改預設的apiInfo資訊 .groupName("Kouch") //分組名稱,配置多個分組-其實就是定義多個Docket物件註冊到spring容器,由spring託管 .enable(flag) .select() .apis(RequestHandlerSelectors.basePackage(
"")) //設定掃描介面的包basePackage(""),withClassAnnotation(RestController.class)) //.paths(PathSelectors.ant("")) //過濾某些訪問路徑下的介面eg:掃描一個controller下的 /hello/xxx路徑下的介面 .build(); } /** * swagger配置: 1、基本資訊 * 配置 swagegr的資訊:apiInfo帶參建構函式 */ private ApiInfo apiInfo(){ Contact contact=new Contact("Kouch", "", ""); //api編寫的作者聯絡 return new ApiInfo( "資料綜控API文件", "2020年暑期基於springboot框架LOL專案API文件", "1.0", "urn:tos", contact, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList()); } /** * swagger配置: 2、分組 * 修改分組名稱:.groupName("Kouch") ; * 配置多個分組:其實就是定義多個Docket物件註冊到spring容器,由spring託管 */ /** * swagger配置: 3、介面掃描 * 指定swagger掃描某些controller定義的介面 * 在Docket例項(執行時註冊)中修改(或者說過濾要掃描的介面) */ /** * swagger配置: 4 實體類掃描 * 只要在controller中返回值中有一個實體類(返回了一個實體類)swagger就會掃描到 * 在掃描的實體類文件中加入註釋 * 在原始碼的實體類中加入註釋:@ApiModel("中文解釋")-類註釋;@ApiModelProperty("中文解釋")-類屬性註釋 */ /** * swagger配置: 5 加註釋 * (1)在實體類中加註釋 * @ApiModel("中文解釋")-類註釋;@ApiModelProperty("中文解釋")-類屬性註釋 * (2)在介面方法(controller的某一個方法加史昂註釋) * @ApiOperation("中文解釋")-方法上加;@ApiParam("中文解釋")-方法中的引數加註釋 * (3)在controller類上加註解 * @@Api(tags = "中文解釋") */ }

     <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>