Home > Java > javaTutorial > body text

SpringBoot project integrates Swagger and swagger-bootstrap-ui and what are the common annotations?

WBOY
Release: 2023-05-24 12:22:13
forward
1922 people have browsed it

    1. Foreword

    With the popularity of front-end and back-end separation in Internet projects, the front-end and back-end are developed by different personnel, and project communication costs also increase. Increase accordingly.

    Mainly reflected in the communication of WebAPI interfaces, Swagger2 emerged as the times require. It can dynamically generate Api interface documents, reduce communication costs, and promote efficient project development.

    Let’s discuss the integration of Swagger2 and swagger-bootstrap-ui on SpringBoot

    2. SpringBoot project integration with swagger

    1. Introduce dependencies

            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger2</artifactId>
                <version>2.8.0</version>
            </dependency>
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger-ui</artifactId>
                <version>2.8.0</version>
            </dependency>
    Copy after login

    2 . Write the configuration file

    You can make corresponding modifications

    @Configuration
    @EnableSwagger2
    @EnableSwaggerBootstrapUI
    @Profile({"dev","test"})
    public class Swagger2Config {
    
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .groupName("") //指定分组,对应(/v2/api-docs?group=)
                    .pathMapping("") //base地址,最终会拼接Controller中的地址
                    .apiInfo(apiInfo())
                    .select()
                    //为当前包路径
    				// .apis(RequestHandlerSelectors.any())
                    .apis(RequestHandlerSelectors.basePackage("com.riskeys.sd.custom"))
                    .paths(PathSelectors.any())
                    .build();
        }
    
        //构建 api文档的详细信息函数
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    //页面标题
                    .title("XXX API对接文档")
                    .description("XX API对接文档") //描述
                    //创建人
                    .contact(new Contact("yuhei001", "https://blog.csdn.net/Yuhei0", "18616591658@163.com"))
                    //版本号
                    .version("1.0")
                    //描述
                    .description("API 描述")
                    .build();
        }
    }
    Copy after login

    3. Start the access page

    http://127.0.0.1:10086/swagger-ui.html

    SpringBoot project integrates Swagger and swagger-bootstrap-ui and what are the common annotations?

    3. SpringBoot project integration swagger-bootstrap-ui

    Perform the following operations based on step 2

    1.Introduce dependencies

            <dependency>
                <groupId>com.github.xiaoymin</groupId>
                <artifactId>swagger-bootstrap-ui</artifactId>
                <version>1.9.6</version>
            </dependency>
    Copy after login

    2. Configure resource processing rules

    If not configured, access error.9996 may be reported.

    Implement the WebMvcConfigurer interface, or WebMvcConfigurationSupport (old version of SpringBoot), implement the addResourceHandlers method, and add the following code.

    @Configuration
    public class AppWebConfig extends WebMvcConfigurationSupport{
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
            // 解决 doc.html 404 报错
            registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
            registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
    
    }
    Copy after login

    or

    @Configuration
    public class AppWebConfig extends WebMvcConfigurationSupport{
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
            // 解决 doc.html 404 报错
            registry.addResourceHandler("doc.html").addResourceLocations("classpath*:/META-INF/resources/");
            registry.addResourceHandler("/webjars/**").addResourceLocations("classpath*:/META-INF/resources/webjars/");
        }
    }
    Copy after login

    In addition, you can also implement rewriting on the startup class

    @SpringBootApplication
    public class XXXApplication  implements WebMvcConfigurer{
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("doc.html").addResourceLocations("classpath*:/META-INF/resources/");
            registry.addResourceHandler("/webjars/**").addResourceLocations("classpath*:/META-INF/resources/webjars/");
        }
    }
    Copy after login

    3. Start the access page

    Access http:// 127.0.0.1:10086/doc.html, compared to swagger-ui.html, this document is cleaner.

    SpringBoot project integrates Swagger and swagger-bootstrap-ui and what are the common annotations?

    4. Introduction to Swagger common annotations

    swagger generates interface documents through annotations, including interface names, request methods, parameters, return information, etc.

    1. Relevant swagger annotations in Swagger2Config

    1.1 @EnableSwagger2 Enable Swagger

    Actuates the configuration class or startup class

    1.2 @EnableSwaggerBootstrapUI Turn on the SwaggerBootstrapUi enhanced function

    Acts on the configuration class or startup class. If you do not use the enhanced function, you do not need to enable it.

    2. Related swagger annotations in controller

    2.1 @Api: Modify the entire class and describe the role of Controller

    value and tags are descriptions. Tags can be used instead of value

    @Api(value = "保险公司列表查询", tags = {"保险公司列表查询"})
    Copy after login

    2.2 @ApiOperation() is used for methods; represents the operation of an http request

    @ApiOperation(value = "信息员保存(注册)/更新", tags = {"信息員保存"}, notes = "messenger desc")
    Copy after login

    2.3 @ApiParam is used Method, parameter, field description; indicates the added metadata for the parameter (description or whether it is required, etc.)

    Applies to a single parameter

    @ApiParam(name="sdMessengerInfo",value="参数描述",required=true)
    Copy after login

    2.4 Request parameter annotation, which can be combined

    • @ApiImplicitParams is used for methods and contains multiple @ApiImplicitParam

    • @ApiImplicitParam is used for methods, Represents separate request parameters

    Suitable for describing multiple parameters

    Example:

    // 组合使用
    @ApiImplicitParams ({
        @ApiImplicitParam(name = "id", value = "参数中文描述", required = true)
    })
    // 单独使用
    @ApiImplicitParam(paramType="query", name="id", dataType="String", required=true, value="参数描述")
    Copy after login

    Note that when @ApiParam and @ApiImplicitParam exist at the same time When, the description of @ApiImplicitParam shall prevail.

    2.5 @ApiIgnore() Used on classes or methods, it does not need to be displayed on the page by swagger, and is rarely used.

    2.6 Response configuration

    • @ApiResponses

    • ##@ApiResponse

    • // 单独配置
      @ApiResponse(code = 400, message = "Invalid user supplied")
      // 组合使用
      @ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })
      Copy after login
    2.7

    @ResponseHeader Response header settings

    @ResponseHeader(name="head1",description="response head conf")
    Copy after login

    3. Related swagger annotations in Model

    3.1

    @ApiModel Used for classes; indicates description of the class, used to receive parameters using entity classes.

    @ApiModel(value = "demo", description = "对象描述")
    Copy after login

    Generally value and desc can be omitted

    3.2

    @ApiModelProperty Used for methods and fields; indicates description of model attributes or data operation changes

    @ApiModelProperty(value = "用户id",name = "openid2",dataType = "String", required = true, hidden = true)
    Copy after login
    • value–Field description

    • ##name

      –Rewrite attribute name

    • dataType

      –Override attribute type

    • ##required
    • –Is it required

    • example
    • –Example

    • hidden
    • –Hide

      Generally, only value and required are marked.

    The above is the detailed content of SpringBoot project integrates Swagger and swagger-bootstrap-ui and what are the common annotations?. For more information, please follow other related articles on the PHP Chinese website!

    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!