Swagger實(shí)現(xiàn)動態(tài)條件注入與全局?jǐn)r截功能詳細(xì)流程
背景
Swagger 可以提供 API 操作的測試文檔,本文記錄 Swagger 使用過程中遇到的兩個小問題:
- 全局響應(yīng)結(jié)果進(jìn)行包裝后導(dǎo)致 Swagger 請求響應(yīng)結(jié)果無法解析,如果項(xiàng)目中配置了
ResponseBodyAdvice實(shí)現(xiàn)類,重寫了beforeBodyWrite方法對響應(yīng)結(jié)果進(jìn)行統(tǒng)一時,應(yīng)該排除 Swagger2 的兩個 URLv2/api-docs和swagger-resources。 - Swagger 注入條件區(qū)分測試和生產(chǎn)環(huán)境的配置的 ETL 不同語法對默認(rèn)無配置的處理結(jié)果。
Swagger2 使用流程
Swagger 用法很簡單,加入引用,一個配置就可以為應(yīng)用提供接口測試界面。
第一步,引入依賴。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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.0</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.8.5</version>
</dependency>
第二步,添加 Swagger 配置類。
@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
@ConditionalOnExpression("'${swagger.enable}'.equalsIgnoreCase('true')")
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("XXX 文檔")
.version("1.0")
.build();
}
}
第三步,為 Web 請求設(shè)置 Api 配置。
@GetMapping("/set")
@ApiOperation(value = "設(shè)置 Session")
public Object Index(HttpServletRequest request){
request.getSession().setAttribute("userUid", "111111");
return request.getSession().getAttribute("userUid");
}
條件配置分析
@ConditionalOnExpression("'${swagger.enable}'.equalsIgnoreCase('true')")這種方式,表達(dá)式成立的條件有兩項(xiàng) swagger.enable 必須配置,且值為 true 時,才會成立。
另外一種寫法:
@ConditionalOnExpression("${swagger.enable:true}")如果未配置屬性 swagger.enable,那么根據(jù) ConditionalOnExpression 注解的默認(rèn)值是 true ,所以就會執(zhí)行注解配置。
啟示錄
為了方便開發(fā)測試,默認(rèn)無配置時視為滿足條件,生產(chǎn)環(huán)境下配置值為 false 是可以的。
到此這篇關(guān)于Swagger實(shí)現(xiàn)動態(tài)條件注入與全局?jǐn)r截功能詳細(xì)流程的文章就介紹到這了,更多相關(guān)Swagger動態(tài)條件注入內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot創(chuàng)建動態(tài)定時任務(wù)的幾種方式小結(jié)
SpringBoot提供了多種實(shí)現(xiàn)定時任務(wù)的方式,包括使用@Scheduled注解、SchedulingConfigurer接口、TaskScheduler接口和Quartz框架,@Scheduled適合簡單的定時任務(wù),文中通過代碼示例介紹的非常詳細(xì),需要的朋友可以參考下2024-10-10
GSON實(shí)現(xiàn)Java對象與JSON格式對象相互轉(zhuǎn)換的完全教程
GSON是Google編寫并在在GitHub上開源的Java序列化與反序列化JSON的類庫,今天我們就來總結(jié)一下使用GSON實(shí)現(xiàn)Java對象與JSON格式對象相互轉(zhuǎn)換的完全教程2016-06-06
springboot 自定義權(quán)限標(biāo)簽(tld),在freemarker引用操作
這篇文章主要介紹了springboot 自定義權(quán)限標(biāo)簽(tld),在freemarker引用操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09

