1. 程式人生 > >SpringMVC註解配置Swagger2步驟及相關知識點

SpringMVC註解配置Swagger2步驟及相關知識點

Swagger2的功能不多說了,百度一下隨處可見,配置步驟也十分簡單,但一些點百度到的很多都不太詳細,個人進行了一些補充

1、pom.xml新增swagger2依賴(個人一般直接到http://search.maven.org/搜尋artifactid點最新版本copy到pom裡)

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.6.1</version>
</dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.6.1</version> </dependency>

2、新增設定swagger2配置類

package pers.graduation.config;

import com.google.common.collect.Sets;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
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;

/**
 * Created by Wilson on 2017/5/2.
 */
@Configuration
@EnableSwagger2
@EnableWebMvc
@ComponentScan(basePackages = "pers.graduation.controller")
public class SwaggerConfig extends WebMvcConfigurationSupport {
    @Bean
    public Docket commonDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("通用API介面文件")
                .apiInfo(apiInfo("提供通用介面"))
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("pers.graduation.controller.common"))
                .paths(PathSelectors.any())
                .build();
    }

    @Bean
    public Docket normalUserDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("普通使用者API文件")
                .apiInfo(apiInfo("提供普通使用者介面"))
                .protocols(Sets.newHashSet("https","http"))
                .produces(Sets.newHashSet("html/text"))
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("pers.graduation.controller.candidate"))//設定生成的Docket對應的Controller為candidate下的所有Controller
                .paths(PathSelectors.any())
                .build();
    }

    @Bean
    public Docket companyUserDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("企業使用者API介面文件")
                .apiInfo(apiInfo("提供企業使用者介面"))
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("pers.graduation.controller.company"))
                .paths(PathSelectors.any())
                .build();
    }
	
//設定文件資訊 private ApiInfo apiInfo(String desc) { return new ApiInfo( "Test Website", //標題名稱 desc, //文件描述 "1.0.1", //版本號,自定義 "http://blog.csdn.net/z28126308", //許可人URL contact(), //聯絡方式實體類 "Wilson",
//許可人,許可證 "http://blog.csdn.net/z28126308"); //許可URL } //設定聯絡方式 private Contact contact() { return new Contact("Wilson", "http://blog.csdn.net/z28126308", "[email protected]"); } }
Docket類的方法:

Docket groupName(String var):設定欄目名

Docket apiInfo(ApiInfo apiInfo):設定文件資訊

Docket pathMapping(String path):設定api根路徑

Docket protocols(Set<String> protocols):設定協議,Sets為com.goolge.common下的類,Sets.newHashSet("https","http")相當於new HashSet(){{add("https");add("http");}};

ApiSelectorBuilder select():初始化並返回一個API選擇構造器


ApiSelectorBuilder類的方法:

ApiSelectorBuilder apis(Predicate<RequestHandler> selector):新增選擇條件並返回新增後的ApiSelectorBuilder物件

ApiSelectorBuilder paths(Predicate<String> selector):設定路徑篩選,該方法中含一句pathSelector = and(pathSelector, selector);表明條件為相與


RequestHandlerSelectors類的方法:

Predicate<RequestHandler> any():返回包含所有滿足條件的請求處理器的斷言,該斷言總為true

Predicate<RequestHandler> none():返回不滿足條件的請求處理器的斷言,該斷言總為false

Predicate<RequestHandler> basePackage(final String basePackage):返回一個斷言(Predicate),該斷言包含所有匹配basePackage下所有類的請求路徑的請求處理器


PathSelectors類的方法:

Predicate<String> any():滿足條件的路徑,該斷言總為true

Predicate<String> none():不滿足條件的路徑,該斷言總為false

Predicate<String> regex(final String pathRegex):符合正則的路徑

不講太多,有興趣的去看原始碼

3、設定swagger-ui.html預設路徑,servlet的配置檔案新增

<mvc:annotation-driven></mvc:annotation-driven>
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars"/>

swagger-ui.html位於springfox-swagger-ui jar包中的META-INF/resources/目錄下,專案編譯後swagger-ui.html將新增到classpath的/META-INF/resources/下,所以新增mapping="/webjars/**" 可通過localhost:埠號/專案名/swagger-ui.html開啟SwaggerUI

4、常用註解

Swagger所有註解並非必須,若不加就只顯示類目/方法名/引數名沒有註釋而已,但若註解中含@ApiParam不對應@RequestParam將無效果

@Api:註解controller,value為@RequestMapping路徑

@ApiOperation:註解方法,value為簡要描述,notes為全面描述,hidden=true Swagger將不顯示該方法,預設為false

@ApiParam:註解引數,hidden=true Swagger引數列表將不顯示該引數,name對應引數名,value為註釋,defaultValue設定預設值,allowableValues設定範圍值,required設定引數是否必須,預設為false

@ApiModel:註解Model

@ApiModelProperty:註解Model下的屬性,當前端傳過來的是一個物件時swagger中該物件的屬性註解就是ApiModelProperty中的value

@ApiIgnore:註解類、引數、方法,註解後將不在Swagger UI中顯示


效果圖(若要傳送物件作為引數,只需新增@ModelAttribute或@RequestBody):


傳送物件引數:

model:

private String telephone;

@Column
private String email;

@Column
private Long companyId;

@Transient
private ComCompany comCompany;

@Transient
private List<PositionWelfare> welfareList;

Controller方法:

@ResponseBody
@RequestMapping(value = "/per-addPosition", method = RequestMethod.POST)
@ApiOperation(value = "新增職位")
public Object addPosition(@ModelAttribute ComPosition position, @RequestParam String[] welfareName) {
Swagger