SpringBoot整合Swagger2的示例
阿新 • • 發佈:2020-11-07
一、匯入maven包
<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>
二、新增工具類
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .pathMapping("/") .select() .apis(RequestHandlerSelectors.basePackage("com.nvn.controller")) .paths(PathSelectors.any()) .build().apiInfo(new ApiInfoBuilder() .title("SpringBoot整合Swagger") .description("SpringBoot整合Swagger,詳細資訊......") .version("1.0") .build()); } }
三、添加註解
@RestController @Api(tags = "使用者管理相關介面") @RequestMapping("/user") public class UserController { @PostMapping("/") @ApiOperation("新增使用者的介面") @ApiImplicitParams({ @ApiImplicitParam(name = "username",value = "使用者名稱",defaultValue = "李四"),@ApiImplicitParam(name = "address",value = "使用者地址",defaultValue = "深圳",required = true) } ) public RespBean addUser(String username,@RequestParam(required = true) String address) { return new RespBean(); } @GetMapping("/") @ApiOperation("根據id查詢使用者的介面") @ApiImplicitParam(name = "id",value = "使用者id",defaultValue = "99",required = true) public User getUserById(@PathVariable Integer id) { User user = new User(); user.setId(id); return user; } @PutMapping("/{id}") @ApiOperation("根據id更新使用者的介面") public User updateUserById(@RequestBody User user) { return user; } }
四、註解說明
- @Api註解可以用來標記當前Controller的功能。
- @ApiOperation註解用來標記一個方法的作用。
- @ApiImplicitParam註解用來描述一個引數,可以配置引數的中文含義,也可以給引數設定預設值,這樣在介面測試的時候可以避免手動輸入。
- 如果有多個引數,則需要使用多個@ApiImplicitParam註解來描述,多個@ApiImplicitParam註解需要放在一個@ApiImplicitParams註解中。
- @ApiImplicitParam註解中雖然可以指定引數是必填的,但是卻不能代替@RequestParam(required = true),前者的必填只是在Swagger2框架內必填,拋棄了Swagger2,這個限制就沒用了,所以假如開發者需要指定一個引數必填,@RequestParam(required = true)註解還是不能省略。
五、如果引數是一個物件,對於引數的描述可以放在實體類中。
@ApiModel public class User { @ApiModelProperty(value = "使用者id") private Integer id; @ApiModelProperty(value = "使用者名稱") private String username; @ApiModelProperty(value = "使用者地址") private String address; //getter/setter }
六、效果
附:如果我們的Spring Boot專案中集成了Spring Security,那麼如果不做額外配置,Swagger2文件可能會被攔截,此時只需要在Spring Security的配置類中重寫configure方法,新增如下過濾即可:
@Override public void configure(WebSecurity web) throws Exception { web.ignoring() .antMatchers("/swagger-ui.html") .antMatchers("/v2/**") .antMatchers("/swagger-resources/**"); }
以上就是SpringBoot整合Swagger2的示例的詳細內容,更多關於SpringBoot整合Swagger2的資料請關注我們其它相關文章!