Springboot集成Swagger2以及常見配置(無坑版)
這種整合的文章確實已經(jīng)爛大街了,寫他一方面是補充我的springboot系列,另一方面確實還有一部分小伙伴沒用過。最重要的是,如果你忘記了這種整合的代碼??梢噪S時查閱。
前言
現(xiàn)在的開發(fā)基本上都是前后端分離,前后端交互都是通過API文檔。有了API文檔大家各自開發(fā),互不干擾。
1、傳統(tǒng)方式
傳統(tǒng)方式是文檔設(shè)計好之后,分別發(fā)給前端和后端人員。這樣有個缺點,接口信息一旦變化,文檔就需要重新發(fā)送給前后端人員。無法做到實時。所以浪費時間和精力。
2、swagger方式
我們的后臺應(yīng)用集成了swagger之后,會自動暴露出我們的接口,而且這個接口形式還是通過restful風格發(fā)布的。一旦后端的接口有變化,會立刻顯示出來,因此極大地提高了效率。
OK,基本上一句話就可以總結(jié)他的好處,那就是后端寫的api文檔可以通過swagger的形式實時的發(fā)布出來,供前端人員查看。
3、其他方式
swagger的頁面說實話長得不好看,也有一些其他的方案,不是有很多bug,就是收費。目前swagger是使用的最多的。我目前也正在做這個樣的開源項目,基于swagger做出類似于其他方案的頁面,而且功能更加的強大。
一、代碼整合
前提條件是要新建一個springboot項目。這點就不演示了。
第一步:添加依賴
- <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>
2.9.2的版本是用的最多的,具體的可以直接去maven的官網(wǎng)去搜索,找一個使用量最多的版本即可。
第二步:配置
新建config包,創(chuàng)建SwaggerConfig類
- @EnableSwagger2
- @Configuration
- public class Swagger2Config {
- @Bean
- public Docket createRestApi() {
- return new Docket(DocumentationType.SWAGGER_2)
- .apiInfo(apiInfo())
- .select()
- //為當前包路徑,控制器類包
- .apis(RequestHandlerSelectors.basePackage("com.fdd.controller"))
- .paths(PathSelectors.any())
- .build();
- }
- //構(gòu)建 api文檔的詳細信息函數(shù)
- private ApiInfo apiInfo() {
- return new ApiInfoBuilder()
- //頁面標題
- .title("XX平臺API接口文檔")
- //創(chuàng)建人
- .contact(new Contact("馮冬冬", "http://www.javachat.cc",
- "3049352171@qq.com"))
- //版本號
- .version("1.0")
- //描述
- .description("系統(tǒng)API描述")
- .build();
- }
這里的配置也比較簡單。這里有很多選項供我們?nèi)ヅ渲谩H绻覀兊捻椖坑卸鄠€組,只需要創(chuàng)建多個Docket即可。這時候掃描的包換成每個組的包路徑。
第三步:controller類中配置
新建一個controller包,然后創(chuàng)建HelloController類
- @Api("Hello控制類")
- @RestController
- public class HelloController {
- @GetMapping(value = "/user")
- public User getUser(){
- return new User("愚公要移山","123456");
- }
- @ApiOperation("可以指定參數(shù)的API")
- @PostMapping("/param")
- public String hello2(@ApiParam("用戶名") String name){
- return "hello" + name;
- }
- }
這里我們可以看出,使用注解就可以對這個類、方法、字段等等進行解釋說明。其他的字段還有很多,在使用的時候會有相應(yīng)的提示,可以自己試一遍:
第四步:查看效果
訪問:http://127.0.0.1:8080/swagger-ui.html即可。
這里就是最終的展示效果。OK,到這一步基本上就集成進來了。下面說一下可能會遇到的配置。
三、常見其他問題
1、Spring Security - 配置免認證訪問
有時候我們的Springboot集成了SpringSecurity,這時候如果訪問swagger的地址會自動跳轉(zhuǎn)到登錄頁面。這是因為SpringSecurity對其進行了攔截。為此我們只需要在我們的SpringSecurity配置一下進行放行即可。
現(xiàn)在配置一下,進行放行。在config包下新建一個SpringSecurityConfig類
- @Configuration
- @EnableWebSecurity
- public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .antMatchers("/swagger-ui.html").permitAll()
- .antMatchers("/webjars/**").permitAll()
- .antMatchers("/swagger-resources/**").permitAll()
- .antMatchers("/v2/*").permitAll()
- .antMatchers("/csrf").permitAll()
- .antMatchers("/").permitAll()
- .anyRequest().authenticated()
- .and()
- .formLogin()
- ;
- }
- }
此時就可以正常的訪問了。
2、為swagger設(shè)置jwt
這種方式比較簡單,只需要一步即可。修改我們的swaggerConfig類即可。
- @EnableSwagger2
- @Configuration
- public class Swagger2Config {
- @Bean
- public Docket api() {
- return new Docket(DocumentationType.SWAGGER_2)
- .apiInfo(apiInfo())
- .securityContexts(Arrays.asList(securityContext()))
- .securitySchemes(Arrays.asList(apiKey()))
- .select()
- .apis(RequestHandlerSelectors.any())
- .paths(PathSelectors.any())
- .build();
- }
- //構(gòu)建 api文檔的詳細信息函數(shù)
- private ApiInfo apiInfo() {
- return new ApiInfoBuilder()
- //頁面標題
- .title("XX平臺API接口文檔")
- //創(chuàng)建人
- .contact(new Contact("馮冬冬", "http://www.javachat.cc",
- "3049352171@qq.com"))
- //版本號
- .version("1.0")
- //描述
- .description("系統(tǒng)API描述")
- .build();
- }
- private ApiKey apiKey() {
- return new ApiKey("JWT", "Authorization", "header");
- }
- private SecurityContext securityContext() {
- return SecurityContext.builder().securityReferences(defaultAuth()).build();
- }
- private List<SecurityReference> defaultAuth() {
- AuthorizationScope authorizationScope
- = new AuthorizationScope("global", "accessEverything");
- AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
- authorizationScopes[0] = authorizationScope;
- return Arrays.asList(new SecurityReference("JWT", authorizationScopes));
- }
- }
加了一些token驗證的代碼,比較簡單,關(guān)于JWT的東西,可以私下了解。這里不贅述了。
3、隱藏Endpoint
有時候自己寫的controller,或者是controller里面的接口方法不想讓前端人員看到,我們可以隱藏即可。
第一:隱藏整個controller
- @ApiIgnore
- @RestController
- public class MyController {
- //方法
- }
第二:隱藏某個接口方法1
- @ApiIgnore
- @ApiOperation(value = "描述信息")
- @GetMapping("/getAuthor")
- public String getAuthor() {
- return "愚公要移山";
- }
第三:隱藏某個接口方法2
- @ApiOperation(value = "描述信息", hidden = true)
- @GetMapping("/get")
- public LocalDate getDate() {
- return LocalDate.now();
- }
OK,很多配置基本上就到這了。后續(xù)會繼續(xù)補充。
本文轉(zhuǎn)載自微信公眾號「愚公要移山」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系愚公要移山公眾號。