SpringBoot整合Swagger3-第三方UI:Knife4j

Swagger3介绍

开发中有很多接口的开发,接口需要配合完整的接口文档才更方便沟通、使用,Swagger是一个用于自动生成在线接口文档的框架,并可在线测试接口,可以很好的跟Spring结合,只需要添加少量的代码和注解即可,而且在接口变动的同时,即可同步修改接口文档,不用再手动维护接口文档。Swagger3是17年推出的最新版本,相比于Swagger2配置更少,使用更方便

开发环境

. JDK 1.8
. SpringBoot 2.4.2

添加Maven依赖



    io.springfox
    springfox-boot-starter
    3.0.0


    com.github.xiaoymin
    knife4j-spring-boot-starter
    
    3.0.3

添加Swagger配置类

package com.epwcloud.common.core.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.Collections;
import java.util.List;

/**
 * Swagger生成api文档
 * Created by 谭月浩 on 2021-11-21 11:42
 */
@EnableOpenApi
@Configuration
public class Swagger3Config {
    @Value("${swagger.host:}")
    private String host;

    @Bean
    public Docket createRestApi() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2);
        if ((host != null && !host.trim().isEmpty())) docket.host(host);
        return docket
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.epwcloud"))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("API文档")
                .description("")
                .version("0.1")
                .termsOfServiceUrl("")
                .build();
    }

    private List securitySchemes() {
        return Collections.singletonList(new ApiKey("Authorization", "Authorization", "header"));
    }

    private List securityContexts() {
        AuthorizationScope[] scopes = {new AuthorizationScope("global", "accessEverything")};
        List references = Collections.singletonList(new SecurityReference("Authorization", scopes));
        return Collections.singletonList(SecurityContext.builder()
                .securityReferences(references)
                .forPaths(PathSelectors.any())
                .build());
    }

}

SecurityConfig配置拦截

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .antMatchers(HttpMethod.GET, "/favicon.ico", "/api/file/**", "/", "/assets/**", "/**.html")
                .permitAll()
                .antMatchers("/api/login", "/error", "/druid/**", "/webjars/**", "/swagger-ui.html",
                        "/swagger-resources/**", "/v3/api-docs","/doc.html").permitAll()
                .anyRequest().authenticated()
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().headers().frameOptions().disable()
                .and().cors().and().csrf().disable();
        http.exceptionHandling().accessDeniedHandler(jwtExceptionHandler()).authenticationEntryPoint(jwtExceptionHandler());
        http.logout().logoutUrl("/logout").logoutSuccessHandler(jwtLogoutSuccessHandler());
        http.addFilterBefore(jwtLoginFilter(), UsernamePasswordAuthenticationFilter.class);
        http.addFilterBefore(jwtRequestFilter(), UsernamePasswordAuthenticationFilter.class);
    }

使用Swagger

  1. 在接口类上添加@Api(tags = "操作接口"),tags的值是该类的作用,在文档页面会显示,value不会显示
  2. 在需要生成文档的接口上添加注解@ApiOperation
  3. 对请求参数添加@ApiParam

示例如下:

@Api(tags = "操作接口")
@RestController
@RequestMapping("hs")
public class HsApi {

    @Resource
    private HsService hsService;

    @Resource
    private HsTypeService hsTypeService;

    @ApiOperation("添加")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名字", dataType = "String", required = true),
            @ApiImplicitParam(name = "typeId", value = "类型ID", dataType = "Long", required = true)
    })
    @PutMapping("add")
    public JSONObject add(String name, Long typeId){
        HsType hsType = hsTypeService.findById(typeId);
        Hs hs = new Hs();
        hs.setName(name);
        hs.setType(hsType);
        hs.setDateCreated(new Date());
        hs = hsService.save(hs);
        return JSONObject.parseObject(JSONObject.toJSONString(hs));
    }

    @ApiOperation("获取")
    @GetMapping("get")
    public JSONObject get(@ApiParam(name = "id", value = "数据ID") Long id){
        Hs hs = hsService.findById(id);
        return JSONObject.parseObject(JSONObject.toJSONString(hs));
    }
}

成果展示

启动服务后,就可以查看在线文档了,本地服务的地址是http://localhost:828/doc.html

SpringBoot整合Swagger3-第三方UI:Knife4j_第1张图片

 

你可能感兴趣的:(笔记,json,java,restful,swagger2,spring)