1. 程式人生 > 其它 >電商專案筆記

電商專案筆記

Swagger官網:https://swagger.io/

使用Swagger

環境:

  • SringBoot版本:2.5.6
  • Swagger版本:2.9.2

新建一個SpringBoot專案,匯入Swagger依賴

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

建立Swagger配置類

import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

}

啟動專案,訪問路徑:http://localhost:8080/swagger-ui.html

Swagger配置

可以進行的配置在springfox.documentation.spring.web.plugins.Docket類中。

在SwaggerConfig配置類中進行配置

// 配置Swagger的Docket的Bean例項
@Bean
public Docket docket() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo());
}

// 配置Swagger資訊
public ApiInfo apiInfo() {
    // 作者資訊
    Contact contact = new Contact("hllog", "https://www.cnblogs.com/hllog/", "[email protected]");

    return new ApiInfo("hllog的Swagger API文件",
            "專注於技術",
            "v1.0",
            "https://www.cnblogs.com/hllog/",
            contact,
            "Apache 2.0",
            "http://www.apache.org/licenses/LICENSE-2.0",
            new ArrayList<>());
}

使用Swagger生成文件

@ApiModel("使用者")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    @ApiModelProperty("使用者ID")
    private Integer id;
    @ApiModelProperty("使用者名稱")
    private String name;
    @ApiModelProperty("密碼")
    private String password;
}
@RestController
public class HelloController {
    @ApiOperation("簡單的問候")
    @GetMapping("/hello")
    public String hello() {
        return "Hello Swagger";
    }

    @ApiOperation("獲取使用者")
    @PostMapping(value = "/user")
    public User user() {
        return new User();
    }

    @ApiOperation("對使用者進行問候")
    @GetMapping("/hello2")
    public String hello2(@ApiParam("使用者名稱") String name) {
        return "Hello, " + name;
    }
}

更多的Swagger註解參見io.swagger.annotations包。