xmtrock
发布于 2021-06-01 / 251 阅读
0

Swagger

1、依赖

<!--swagger-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
</dependency>
<!--swagger ui-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
</dependency>

2、配置(可以直接用,不要妄想自己敲)

@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket webApiConfig(){
        ParameterBuilder ticketPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<Parameter>();
        ticketPar.name("Authorization").description("登录校验")
                .modelRef(new ModelRef("string")).parameterType("header")
                .required(false).defaultValue("Bearer ").build(); //header中的ticket参数非必填,传空也可以
        pars.add(ticketPar.build());    //根据每个方法名也知道当前方法在设置什么参数

        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("webApi")
                .apiInfo(webApiInfo())
                .select()// 选择那些路径和api会生成document
                .paths(PathSelectors.any())
                .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
                .build().globalOperationParameters(pars);
    }

    private ApiInfo webApiInfo(){
        return new ApiInfoBuilder()
                .title("网站-API文档")
                .description("本文档描述了网站微服务接口定义")
                .version("1.0")
                .contact(new Contact("腼腆Hold", "https://www.soulike.xyz", "728407682@qq.com"))
                .build();
    }

    // @Bean
    // public Docket adminApiConfig(){
    //
    //     return new Docket(DocumentationType.SWAGGER_2)
    //             .groupName("adminApi")
    //             .apiInfo(adminApiInfo())
    //             .select()
    //             //只显示admin路径下的页面
    //             .paths(Predicates.and(PathSelectors.regex("/admin/.*")))
    //             .build();
    //
    // }
    // private ApiInfo adminApiInfo(){
    //
    //     return new ApiInfoBuilder()
    //             .title("后台管理系统-API文档")
    //             .description("本文档描述了后台管理系统微服务接口定义")
    //             .version("1.0")
    //             .contact(new Contact("腼腆Hold", "https://www.soulike.xyz", "728407682@qq.com"))
    //             .build();
    // }
}

3、扫描

@ComponentScan(basePackages = "com.soulike")

4、controller

//查询医院设置表里面的所有信息
@GetMapping("/findAll")
@ApiOperation(value = "获取所有的医院设置信息")
public List<HospitalSet> findAllHospitalSet() {
    //调用service里面的方法
    List<HospitalSet> list = hospitalSetService.list();
    return list;
}

4、效果:

20210601134735271

排除拦截器

@Override
public void addInterceptors(InterceptorRegistry registry) {
    //1.添加自定义拦截器
    registry.addInterceptor(jwtInterceptor)
            .addPathPatterns("/**")//2.指定拦截器的url地址
            .excludePathPatterns("/sys/login", "/frame/register/**")//3.指定不拦截的url地址
            .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    //将templates目录下的CSS、JS文件映射为静态资源,防止Spring把这些资源识别成thymeleaf模版
    registry.addResourceHandler("/templates/**.js").addResourceLocations("classpath:/templates/");
    registry.addResourceHandler("/templates/**.css").addResourceLocations("classpath:/templates/");
    //其他静态资源
    registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    //swagger增加url映射
    registry.addResourceHandler("swagger-ui.html")
            .addResourceLocations("classpath:/META-INF/resources/");
    registry.addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/");
}

shiro方式排除

//swagger
filterMap.put("/swagger-ui.html", "anon");
filterMap.put("/swagger-resources/**", "anon");
filterMap.put("/v2/**", "anon");
filterMap.put("/webjars/**", "anon");

swagger3

https://juejin.cn/post/6959877018892959775

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
springfox:
  documentation:
    swagger-ui:
      enabled: true
@Configuration
@EnableOpenApi
public class SwaggerConfig implements WebMvcConfigurer {
    @Bean
    public Docket createRestApi() {
        //返回文档摘要信息
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                // .globalRequestParameters(getGlobalRequestParameters())
                .globalResponses(HttpMethod.GET, getGlobalResponseMessage())
                .globalResponses(HttpMethod.POST, getGlobalResponseMessage());
    }

    /**
     * 生成接口信息,包括标题、联系人等
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger3接口文档")
                .description("腼腆Hold开发")
                .contact(new Contact("腼腆Hold", "http://xmtrock.site/", "728407682@qq.com"))
                .version("1.4")
                .build();
    }

    /**
     * 封装全局通用参数
     */
    private List<RequestParameter> getGlobalRequestParameters() {
        List<RequestParameter> parameters = new ArrayList<>();
        parameters.add(new RequestParameterBuilder()
                .name("uuid")
                .description("设备uuid")
                .required(true)
                .in(ParameterType.QUERY)
                .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
                .required(false)
                .build());
        return parameters;
    }

    /**
     * 封装通用响应信息
     */
    private List<Response> getGlobalResponseMessage() {
        List<Response> responseList = new ArrayList<>();
        responseList.add(new ResponseBuilder().code("404").description("未找到资源").build());
        return responseList;
    }
}
@Data
@ApiModel(description = "department部门实体类")
public class Department implements Serializable {
    @ApiModelProperty("部门id")
    private Integer departmentid;
    @ApiModelProperty("部门名字")
    private String departmentname;
}
@RestController
@Api(tags = "swagger查询")
public class DepartmentController {
    @GetMapping("/dep")
    @ApiOperation("查询数据")
    public String getDep(@Parameter(description = "部门id,必须") Integer id) {
        Department dep = departmentService.getDep(id);
        System.out.println(dep.toString());
        return dep.toString();
    }
}

导出文档

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>3.0.2</version>
</dependency>
@EnableKnife4j

2022-06-30_085600