>  기사  >  Java  >  SpringBoot 프로젝트는 Swagger와 swagger-bootstrap-ui를 통합하며 일반적인 주석은 무엇입니까?

SpringBoot 프로젝트는 Swagger와 swagger-bootstrap-ui를 통합하며 일반적인 주석은 무엇입니까?

WBOY
WBOY앞으로
2023-05-24 12:22:131867검색

    1. 소개

    인터넷 프로젝트에서 프론트엔드와 백엔드 분리가 대중화되면서 프론트엔드와 백엔드를 서로 다른 인력이 개발하게 되면서 프로젝트 커뮤니케이션 비용도 증가하게 되었습니다.

    주로 WebAPI 인터페이스의 통신에 반영되어 Api 인터페이스 문서를 동적으로 생성하고 통신 비용을 절감하며 효율적인 프로젝트 개발을 촉진할 수 있는 Swagger2가 탄생했습니다.

    다음은 SpringBoot

    2에서 Swagger2와 swagger-bootstrap-ui를 통합하는 방법에 대해 설명합니다. swagger와 SpringBoot 프로젝트 통합

    1. 구성 파일 작성

    적절하게 비교하고 수정할 수 있습니다.

    3. 액세스 페이지 시작

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

    3. SpringBoot 프로젝트는 swagger-bootstrap-uiSpringBoot 프로젝트는 Swagger와 swagger-bootstrap-ui를 통합하며 일반적인 주석은 무엇입니까?

    2단계를 기반으로 다음 작업을 수행합니다.

    1.종속성 도입

            <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>

    2. 리소스 처리 규칙 구성

    구성되어 있지 않은 경우 접속 시 오류.9996이 보고될 수 있습니다.

    WebMvcConfigurer 인터페이스 또는 WebMvcConfigurationSupport(SpringBoot의 이전 버전)를 구현하고 addResourceHandlers 메서드를 구현한 후 아래 표시된 코드를 추가하세요.

    @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();
        }
    }

    또는

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

    또한 시작 클래스

    @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/");
        }
    
    }

    3에서 다시 작성을 구현할 수도 있습니다. 액세스 페이지를 시작하세요

    http://127.0.0.1:10086/doc.html을 방문하세요. swagger-ui와 비교해보세요. .html 측면에서는 이 문서가 더 신선합니다.

    4. Swagger 일반 주석 소개

    SpringBoot 프로젝트는 Swagger와 swagger-bootstrap-ui를 통합하며 일반적인 주석은 무엇입니까?swagger는 주석을 통해 인터페이스 이름, 요청 방법, 매개변수, 반환 정보 등을 포함한 인터페이스 문서를 생성합니다.

    1. Swagger2Config

    1.1의 관련 Swagger 주석

    @EnableSwagger2

    Swagger 켜기

    구성 클래스 또는 시작 클래스에서 작동1.2

    @EnableSwaggerBootstrapUI

    SwaggerBootstrapUi 개선 사항 켜기

    구성 클래스 또는 시작 클래스에 대해 작동합니다. 향상된 기능을 사용하기 위해 전원을 켤 필요가 없습니다. 2. 컨트롤러의 관련 swagger 주석

    2.1

    @Api

    : 전체 클래스를 수정하고 컨트롤러의 역할을 설명합니다.

    값과 태그는 설명이며, 값 대신 태그를 사용할 수 있습니다

    @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/");
        }
    }
    2.2

    @ApiOperation( )

    이 사용됩니다. 메소드는 http 요청의 작업을 나타냅니다.

    @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/");
        }
    }

    2.3 @ApiParam 메소드, 매개변수, 필드 설명에 사용되며 매개변수에 대한 메타데이터 추가를 나타냅니다(설명 또는 필수 여부 등).

    단일 매개변수에 적용

    @Api(value = "保险公司列表查询", tags = {"保险公司列表查询"})
    2.4 결합 가능한 요청 매개변수 주석

    @ApiImplicitParams

    여러 @ApiImplicitParams를 포함하는 메소드에 사용됨
    • @ApiImplicitParam

      개별 요청 매개변수를 나타내는 메소드에 사용됨
    • 여러 매개변수에 적합한 설명이 있습니다.

      예:
    • @ApiOperation(value = "信息员保存(注册)/更新", tags = {"信息員保存"}, notes = "messenger desc")
    @ApiParam과 @ApiImplicitParam이 동시에 존재할 경우 @ApiImplicitParam의 설명이 우선합니다.

    2.5

    @ApiIgnore()

    클래스나 메소드에 사용되며, 페이지에 swagger로 표시할 필요가 없으며 거의 ​​사용되지 않습니다.

    2.6 응답 구성

    @ApiResponses

    • @ApiResponse

    • @ApiParam(name="sdMessengerInfo",value="参数描述",required=true)
      2.7 @ResponseHeader

      응답 헤더 설정
    • // 组合使用
      @ApiImplicitParams ({
          @ApiImplicitParam(name = "id", value = "参数中文描述", required = true)
      })
      // 单独使用
      @ApiImplicitParam(paramType="query", name="id", dataType="String", required=true, value="参数描述")
    3. Model

    3.1 @ApiModel의 관련 Swagger 주석

    클래스에 사용됩니다. 클래스에 대한 설명을 나타내며 엔터티 클래스를 사용하여 매개변수를 받는 데 사용됩니다.

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

    일반적으로 value 및 desc는 생략 가능

    3.2 @ApiModelProperty

    메서드 및 필드에 사용되며 모델 속성 또는 데이터 작업 변경에 대한 설명을 나타냅니다.

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

    –필드 설명

    • 이름–속성 이름 다시 쓰기

      value–字段说明

    • name–重写属性名字

    • dataType–重写属性类型

    • required–是否必填

    • example–举例说明

    • hidden

    • dataType–속성 유형 다시 쓰기

    🎜필수&ndash ; 필수? 🎜🎜🎜🎜example–Example 🎜🎜🎜🎜hidden–Hide🎜🎜🎜🎜 일반적으로 값과 필수만 표시됩니다. 🎜

    위 내용은 SpringBoot 프로젝트는 Swagger와 swagger-bootstrap-ui를 통합하며 일반적인 주석은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

    성명:
    이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제