十年網(wǎng)站開發(fā)經(jīng)驗 + 多家企業(yè)客戶 + 靠譜的建站團(tuán)隊
量身定制 + 運營維護(hù)+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
這篇文章將為大家詳細(xì)講解有關(guān)SpringBoot中如何使用Swagger,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。
創(chuàng)新互聯(lián)客戶idc服務(wù)中心,提供資陽托管服務(wù)器、成都服務(wù)器、成都主機(jī)托管、成都雙線服務(wù)器等業(yè)務(wù)的一站式服務(wù)。通過各地的服務(wù)中心,我們向成都用戶提供優(yōu)質(zhì)廉價的產(chǎn)品以及開放、透明、穩(wěn)定、高性價比的服務(wù),資深網(wǎng)絡(luò)工程師在機(jī)房提供7*24小時標(biāo)準(zhǔn)級技術(shù)保障。
項目結(jié)構(gòu)
配置文件
@Configuration @EnableSwagger2 public class Swagger2Config { //swagger2的配置文件,可以配置swagger2的一些基本的內(nèi)容,比如掃描的包等等 @Bean public Docket defaultApi(){ return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).groupName("默認(rèn)分組").select() .apis(RequestHandlerSelectors.basePackage("com.chenwenhuan.springbootlearning.controller")) .paths(PathSelectors.any()).build(); } // 預(yù)覽地址:http://localhost:8082/swagger-ui.html#/ private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("整合swagger構(gòu)建測試系統(tǒng)api文檔") .description("接口訪問地址:http://localhost:8082/") .termsOfServiceUrl("http://localhost:8082/") .version("1.0") .build(); } }
pom.xml 新增依賴
io.springfox springfox-swagger2 2.7.0 io.springfox springfox-swagger-ui 2.7.0
Controller注解
@Api(value="用戶api", tags="用戶api") @RestController @RequestMapping("/user") public class UserController { @Autowired UserService userService; @GetMapping("/findAll") public ListfindAll(){ return userService.findAll(); } @ApiOperation(value="獲取用戶信息", notes="根據(jù)url的id來獲取信息") @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "用戶ID", paramType = "query",required = true)}) @GetMapping("/getUser") public User getUser(@RequestParam int id){ return userService.getUserById(id); } @PostMapping("/creatUser") public void creatUser(User user){ System.out.println(user); userService.insert(user); } @PostMapping("/creatUserList") public void creatUserList(@RequestBody List list){ userService.insertList(list); } }
啟動項目訪問預(yù)覽地址 http://localhost:8082/swagger-ui.html#/,效果如下。(可以看出此處很多信息都源自配置Swagger2Config)
示例1
輸入?yún)?shù)點擊Try it out!,可以查看返回碼和返回數(shù)據(jù)
示例2:
參考右邊提示,按格式輸入Json格式的對象數(shù)組
示例3:
controller需要注解 paramType = "query",否則需要按Example Value 格式輸入。required:是否必輸
@ApiImplicitParams({@ApiImplicitParam(name = "id", value = "用戶ID", paramType = "query",required = true)})
關(guān)于SpringBoot中如何使用Swagger就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。