【Java从零到架构师第③季】【48】SpringBoot-Swagger
生活随笔
收集整理的這篇文章主要介紹了
【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
訪問:
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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 200条装修小常识②
- 下一篇: ANSYS Electronic des