日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

【Java从零到架构师第③季】【48】SpringBoot-Swagger

發布時間:2024/1/1 java 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Java从零到架构师第③季】【48】SpringBoot-Swagger 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

持續學習&持續更新中…

守破離


【Java從零到架構師第③季】【48】SpringBoot-Swagger

    • 接口文檔—Swagger
    • 基本使用
        • 不使用starter
        • 使用starter(Swagger3.0)
    • API選擇
    • 忽略參數
    • 分組
    • 參數類型
    • 全局參數
    • 常用注解
    • swagger-bootstrap-ui
    • 項目實際運用
    • 注意
    • 參考

接口文檔—Swagger

https://swagger.io/

<dependency><groupId>io.swagger</groupId><artifactId>swagger-models</artifactId><version>1.6.2</version></dependency>

基本使用

不使用starter

<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 {@Beanpublic Docket docket(Environment environment) {return new Docket(DocumentationType.SWAGGER_2)// 項目上線了就不應該開啟本功能了,以下方式任選其一 // .enable(environment.acceptsProfiles(Profiles.of("dev"))) // 是dev.enable(!environment.acceptsProfiles(Profiles.of("prd"))) // 不是prd.apiInfo(apiInfo());}// @Bean // public Docket docket() { // return new Docket(DocumentationType.SWAGGER_2) .enable(false) // 項目上線了就不應該開啟本功能了 // .apiInfo(apiInfo()); // }private ApiInfo apiInfo() {return new ApiInfoBuilder().title("LP駕考").description("這是一份詳細的API接口文檔").version("1.0.0").build();} }

使用starter(Swagger3.0)

<dependency><groupId>io.springfox</groupId><artifactId>springfox-boot-starter</artifactId><version>3.0.0</version></dependency> @Configuration @EnableOpenApi public class SwaggerConfig {@Autowiredprivate Environment environment;@Beanpublic Docket docket() {return new Docket(DocumentationType.OAS_30).enable(!environment.acceptsProfiles(Profiles.of("prd"))) // 不是prd就開啟文檔接口.apiInfo(apiInfo());}private ApiInfo apiInfo() {return new ApiInfoBuilder().title("LP駕考").description("這是一份詳細的API接口文檔").version("1.0.0").build();} }

API選擇

@Beanpublic Docket docket(Environment environment) {return new Docket(DocumentationType.SWAGGER_2).enable(!environment.acceptsProfiles(Profiles.of("prd"))).apiInfo(apiInfo()).select().paths(PathSelectors.ant("/dict*/**")).build();} @Beanpublic Docket docket(Environment environment) {return new Docket(DocumentationType.SWAGGER_2).enable(!environment.acceptsProfiles(Profiles.of("prd"))).apiInfo(apiInfo()).select().paths(PathSelectors.regex("/dict.+")).build();} @Beanpublic Docket docket(Environment environment) {return new Docket(DocumentationType.SWAGGER_2).enable(!environment.acceptsProfiles(Profiles.of("prd"))).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("programmer.lp.jk.controller")).build();} @Beanpublic Docket docket(Environment environment) {return new Docket(DocumentationType.SWAGGER_2).enable(!environment.acceptsProfiles(Profiles.of("prd"))).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.withClassAnnotation(RestController.class)).build();} @Beanpublic Docket docket(Environment environment) {return new Docket(DocumentationType.SWAGGER_2).enable(!environment.acceptsProfiles(Profiles.of("prd"))).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.withMethodAnnotation(GetMapping.class)).build();}

忽略參數

如果我們想在構建文檔時忽略Controller中方法的某些參數:

@Beanpublic Docket docket(Environment environment) {return new Docket(DocumentationType.SWAGGER_2).enable(!environment.acceptsProfiles(Profiles.of("prd"))).apiInfo(apiInfo()).ignoredParameterTypes(HttpSession.class,HttpServletRequest.class,HttpServletResponse.class).select().apis(RequestHandlerSelectors.basePackage("programmer.lp.jk.controller")).build();}

分組

有多少個分組就得有多少個Docket對象:

@Component @Data @ConfigurationProperties("swagger") public class SwaggerProperties {String title;String version;String name;String url;String email;List<String> ignoredParameterTypes; } swagger:email: xxxx@foxmail.comignored-parameter-types:- javax.servlet.http.HttpSession- javax.servlet.http.HttpServletRequest- javax.servlet.http.HttpServletResponsename: lpruoyuurl: https://blog.csdn.net/weixin_44018671version: 1.0.0title: LP駕考 @Configuration @EnableSwagger2 public class SwaggerConfig implements InitializingBean {@Beanpublic Docket examDocket() {return getDocket("考試","包含模塊:考場、科1科4、科2科3","/exam.*");}@Beanpublic Docket dictDocket() {return getDocket("數據字典","包含模塊:數據字典類型、數據字典條目、省份、城市","/(dict.*|plate.*)");}@Autowiredprivate SwaggerProperties swaggerProperties;@Autowiredprivate Environment environment;private Class[] ignoredParameterTypes;private boolean enable;private Class[] getIgnoredParameterTypes() {final List<Class<?>> iptClasses = new ArrayList<>();swaggerProperties.getIgnoredParameterTypes().forEach(v -> {try {iptClasses.add(Class.forName(v));} catch (ClassNotFoundException e) {e.printStackTrace();}});return iptClasses.toArray(new Class[iptClasses.size()]);}@Overridepublic void afterPropertiesSet() throws Exception {ignoredParameterTypes = getIgnoredParameterTypes();enable = !environment.acceptsProfiles(Profiles.of("prd"));}private Docket getDocket(String groupName, String description, String pathRegex) {return new Docket(DocumentationType.SWAGGER_2).enable(enable).groupName(groupName) // .ignoredParameterTypes( // HttpSession.class, // HttpServletRequest.class, // HttpServletResponse.class // ).ignoredParameterTypes(ignoredParameterTypes).select().paths(PathSelectors.regex(pathRegex)).build().apiInfo(apiInfo(swaggerProperties.getTitle() + groupName, description));}private ApiInfo apiInfo(String title, String description) {return new ApiInfoBuilder().title(title).description(description).version(swaggerProperties.getVersion()).contact(new Contact(swaggerProperties.getName(),swaggerProperties.getUrl(),swaggerProperties.getEmail())).build();} }

參數類型

參數類型有:

  • query 對應 @RequestParam 類型的參數
  • body 對應 @RequestBody 類型的參數
  • header 對應 @RequestHeader 類型的參數

全局參數

使用Swagger-boot-starter 3.0:

public Docket basicDocket() {RequestParameter tokenParam = new RequestParameterBuilder().name(TokenFilter.TOKEN_HEADER).description("用戶登錄令牌").in(ParameterType.HEADER).build();return new Docket(DocumentationType.SWAGGER_2).globalRequestParameters(List.of(tokenParam)).enable(true).ignoredParameterTypes(HttpSession.class,HttpServletRequest.class,HttpServletResponse.class);}

常用注解

swagger-bootstrap-ui

Swagger默認的接口頁面不太好看也不太直觀,可以考慮試試這個:

  • https://doc.xiaominfo.com/knife4j/documentation/
  • https://github.com/xiaoymin/Swagger-Bootstrap-UI
<dependency><groupId>com.github.xiaoymin</groupId><artifactId>swagger-bootstrap-ui</artifactId><version>1.9.6</version></dependency>

訪問:

http://${host}:${port}/${context_path}/doc.html

項目實際運用

<properties><swagger.models.version>1.6.2</swagger.models.version><swagger.triui.version>1.9.6</swagger.triui.version><swagger.version>2.9.2</swagger.version></properties><!-- 接口文檔 --><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>${swagger.version}</version></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>${swagger.version}</version></dependency><dependency><groupId>io.swagger</groupId><artifactId>swagger-models</artifactId><version>${swagger.models.version}</version></dependency><dependency><groupId>com.github.xiaoymin</groupId><artifactId>swagger-bootstrap-ui</artifactId><version>${swagger.triui.version}</version></dependency> @Component @Data @ConfigurationProperties("swagger") public class SwaggerProperties {String title;String version;String name;String url;String email;List<String> ignoredParameterTypes; } swagger:email: xxxx@foxmail.comignored-parameter-types:- javax.servlet.http.HttpSession- javax.servlet.http.HttpServletRequest- javax.servlet.http.HttpServletResponsename: lpruoyuurl: https://blog.csdn.net/weixin_44018671version: 1.0.0title: LP駕考 @Configuration @EnableSwagger2 public class SwaggerConfig implements InitializingBean {@Beanpublic Docket sysDocket() {return getDocket("01_系統","包含模塊:用戶、角色、資源","/sys.*");}@Beanpublic Docket examDocket() {return getDocket("02_考試","包含模塊:考場、科1科4、科2科3","/exam.*");}@Beanpublic Docket dictDocket() {return getDocket("03_數據字典","包含模塊:數據字典類型、數據字典條目、省份、城市","/(dict.*|plate.*)");}@Autowiredprivate SwaggerProperties swaggerProperties;@Autowiredprivate Environment environment;private Class[] ignoredParameterTypes;private boolean enable;private Class[] getIgnoredParameterTypes() {final List<Class<?>> iptClasses = new ArrayList<>();swaggerProperties.getIgnoredParameterTypes().forEach(v -> {try {iptClasses.add(Class.forName(v));} catch (ClassNotFoundException e) {e.printStackTrace();}});return iptClasses.toArray(new Class[iptClasses.size()]);}@Overridepublic void afterPropertiesSet() throws Exception {ignoredParameterTypes = getIgnoredParameterTypes();enable = !environment.acceptsProfiles(Profiles.of("prd"));}private Docket getDocket(String groupName, String description, String pathRegex) {Parameter token = new ParameterBuilder().name("token").description("用戶登錄令牌").parameterType("header").modelRef(new ModelRef("String")).required(false).build();return new Docket(DocumentationType.SWAGGER_2).globalOperationParameters(Arrays.asList(token)).ignoredParameterTypes(ignoredParameterTypes).enable(enable).groupName(groupName).apiInfo(apiInfo(swaggerProperties.getTitle() + groupName, description)).select().apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).paths(PathSelectors.regex(pathRegex)).build();}private ApiInfo apiInfo(String title, String description) {return new ApiInfoBuilder().title(title).description(description).version(swaggerProperties.getVersion()).contact(new Contact(swaggerProperties.getName(),swaggerProperties.getUrl(),swaggerProperties.getEmail())).build();} } - http://localhost:8080/jk/swagger-ui.html- http://localhost:8080/jk/doc.html

注意

  • 如果SpringBoot版本較高,請在application.yml中添加:spring:mvc:pathmatch:matching-strategy: ant_path_matcher

參考

小碼哥-李明杰: Java從0到架構師③進階互聯網架構師.


本文完,感謝您的關注支持!


總結

以上是生活随笔為你收集整理的【Java从零到架构师第③季】【48】SpringBoot-Swagger的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。