本文出自《愚公要移山》
收錄于《Springboot專題》中
這種整合的文章確實(shí)已經(jīng)爛大街了蒂破,寫他一方面是補(bǔ)充我的springboot系列,另一方面確實(shí)還有一部分小伙伴沒用過。最重要的是,如果你忘記了這種整合的代碼攻泼。可以隨時(shí)查閱鉴象。
前言
現(xiàn)在的開發(fā)基本上都是前后端分離忙菠,前后端交互都是通過API文檔。有了API文檔大家各自開發(fā)纺弊,互不干擾牛欢。
1、傳統(tǒng)方式
傳統(tǒng)方式是文檔設(shè)計(jì)好之后淆游,分別發(fā)給前端和后端人員傍睹。這樣有個(gè)缺點(diǎn),接口信息一旦變化犹菱,文檔就需要重新發(fā)送給前后端人員拾稳。無法做到實(shí)時(shí)。所以浪費(fèi)時(shí)間和精力腊脱。
2访得、swagger方式
我們的后臺應(yīng)用集成了swagger之后,會自動(dòng)暴露出我們的接口虑椎,而且這個(gè)接口形式還是通過restful風(fēng)格發(fā)布的震鹉。一旦后端的接口有變化,會立刻顯示出來捆姜,因此極大地提高了效率。
OK迎膜,基本上一句話就可以總結(jié)他的好處泥技,那就是后端寫的api文檔可以通過swagger的形式實(shí)時(shí)的發(fā)布出來,供前端人員查看磕仅。
3珊豹、其他方式
swagger的頁面說實(shí)話長得不好看,也有一些其他的方案榕订,不是有很多bug店茶,就是收費(fèi)。目前swagger是使用的最多的劫恒。我目前也正在做這個(gè)樣的開源項(xiàng)目贩幻,基于swagger做出類似于其他方案的頁面轿腺,而且功能更加的強(qiáng)大。
一丛楚、代碼整合
前提條件是要新建一個(gè)springboot項(xiàng)目族壳。這點(diǎn)就不演示了。
第一步:添加依賴
<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)去搜索仿荆,找一個(gè)使用量最多的版本即可。
第二步:配置
新建config包坏平,創(chuàng)建SwaggerConfig類
@EnableSwagger2
@Configuration
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//為當(dāng)前包路徑,控制器類包
.apis(RequestHandlerSelectors.basePackage("com.fdd.controller"))
.paths(PathSelectors.any())
.build();
}
//構(gòu)建 api文檔的詳細(xì)信息函數(shù)
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//頁面標(biāo)題
.title("XX平臺API接口文檔")
//創(chuàng)建人
.contact(new Contact("馮冬冬", "http://www.javachat.cc",
"3049352171@qq.com"))
//版本號
.version("1.0")
//描述
.description("系統(tǒng)API描述")
.build();
}
這里的配置也比較簡單拢操。這里有很多選項(xiàng)供我們?nèi)ヅ渲谩H绻覀兊捻?xiàng)目有多個(gè)組舶替,只需要?jiǎng)?chuàng)建多個(gè)Docket即可庐冯。這時(shí)候掃描的包換成每個(gè)組的包路徑。
第三步:controller類中配置
新建一個(gè)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;
}
}
這里我們可以看出展父,使用注解就可以對這個(gè)類、方法玲昧、字段等等進(jìn)行解釋說明栖茉。其他的字段還有很多,在使用的時(shí)候會有相應(yīng)的提示孵延,可以自己試一遍:
第四步:查看效果
訪問:http://127.0.0.1:8080/swagger-ui.html即可吕漂。
這里就是最終的展示效果。OK尘应,到這一步基本上就集成進(jìn)來了惶凝。下面說一下可能會遇到的配置。
三犬钢、常見其他問題
1苍鲜、Spring Security - 配置免認(rèn)證訪問
有時(shí)候我們的Springboot集成了SpringSecurity,這時(shí)候如果訪問swagger的地址會自動(dòng)跳轉(zhuǎn)到登錄頁面玷犹。這是因?yàn)镾pringSecurity對其進(jìn)行了攔截混滔。為此我們只需要在我們的SpringSecurity配置一下進(jìn)行放行即可。
現(xiàn)在配置一下歹颓,進(jìn)行放行坯屿。在config包下新建一個(gè)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()
;
}
}
此時(shí)就可以正常的訪問了。
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文檔的詳細(xì)信息函數(shù)
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//頁面標(biāo)題
.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驗(yàn)證的代碼吠昭,比較簡單喊括,關(guān)于JWT的東西,可以私下了解怎诫。這里不贅述了瘾晃。
3、隱藏Endpoint
有時(shí)候自己寫的controller幻妓,或者是controller里面的接口方法不想讓前端人員看到蹦误,我們可以隱藏即可。
第一:隱藏整個(gè)controller
@ApiIgnore
@RestController
public class MyController {
//方法
}
第二:隱藏某個(gè)接口方法1
@ApiIgnore
@ApiOperation(value = "描述信息")
@GetMapping("/getAuthor")
public String getAuthor() {
return "愚公要移山";
}
第三:隱藏某個(gè)接口方法2
@ApiOperation(value = "描述信息", hidden = true)
@GetMapping("/get")
public LocalDate getDate() {
return LocalDate.now();
}
OK肉津,很多配置基本上就到這了强胰。后續(xù)會繼續(xù)補(bǔ)充。