springboot 集成swagger2【简单使用】

Swagger简介

  • 号称世界上最流行的Api框架
  • RestFul Api 文档在线自动生成工具 => Api文档与 Api 实时同步更新
  • 直接运行,可以在线测试API接口;
  • 支持多种语言:(java,php…)

官网: https://swagger.io/

在项目中使用Swagger需要 springbox;

  • seagger2
  • ui

SpringBoot 集成 Swagger

  1. 导入相关依赖
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
  1. 编写配置类Swagger ==> config
@Configuration
@EnableSwagger2
public class SwaggerConfig {

}
  1. 运行测试: http://localhost:9000/swagger-ui.html#/
    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-e6aAK10c-1594459376760)(images/1593880037675.png)]

配置Swagger

Swagger的实例 Docket

/**
 * 开启Swagger2
 * @author akieay
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    /**
     * 配置Swagger的 Docket 的Bean实例
     * @return
     */
    @Bean
    public Docket docker(Environment environment){
        //设置要显示的Swagger环境
        Profiles profiles = Profiles.of("dev", "test");
        //通过environment.acceptsProfiles 判断是否处于指定环境中
        boolean flag = environment.acceptsProfiles(profiles);

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                //设置分组名称
                .groupName("akieay_blog")
                //是否启动Swagger,若为false,则在浏览器中无法访问
                .enable(flag)
                .select()
                /**
                 * 配置要扫描的接口方式, basePackage: 根据包路径扫描;any: 扫描全部;none: 全部不扫描;
                 * withClassAnnotation: 根据类上的注解扫描 eg: @RestController
                 * withMethodAnnotation: 根据方法上的注解扫描 eg: @GetMapping
                 */
                .apis(RequestHandlerSelectors.basePackage("com.*.*.*.controller"))
                /**
                 * 扫描指定的路径
                 */
                .paths(PathSelectors.ant("/blog/**"))
                .build();
    }

	/**
	* 简介
	*/
    private ApiInfo apiInfo(){
        return new ApiInfo(
                "Akieay Blog 官方接口文档",
                "前进吧,如果你还没有放弃的话。。。",
                "1.0",
                "https://www.akieay.com/",
                new Contact("akieay", "https://www.akieay.com/", "savesl@163.com"),
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList());
    }

}

在这里插入图片描述

Swagger注解

@Api:用在请求的类上,表示对类的说明
    tags="说明该类的作用,可以在UI界面上看到的注解"
    value="该参数没什么意义,在UI界面上也看到,所以不需要配置"

@ApiOperation:用在请求的方法上,说明方法的用途、作用
    value="说明方法的用途、作用"
    notes="方法的备注说明"
    
@ApiParam()用于方法,参数,字段说明; 
表示对参数的添加元数据(说明或是否必填等) 

@ApiImplicitParams:用在请求的方法上,表示一组参数说明
    @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
        name:参数名
        value:参数的汉字说明、解释
        required:参数是否必须传
        paramType:参数放在哪个地方
            · header --> 请求参数的获取:@RequestHeader
            · query --> 请求参数的获取:@RequestParam
            · path(用于restful接口)--> 请求参数的获取:@PathVariable
            · body(不常用)
            · form(不常用)    
        dataType:参数类型,默认String,其它值dataType="Integer"       
        defaultValue:参数的默认值

@ApiResponses:用在请求的方法上,表示一组响应
    @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
        code:数字,例如400
        message:信息,例如"请求参数没填好"
        response:抛出异常的类

@ApiModel:用于响应类上,表示一个返回响应数据的信息
            (这种一般用在post创建的时候,使用@RequestBody这样的场景,
            请求参数无法使用@ApiImplicitParam注解进行描述的时候)
    @ApiModelProperty:用在属性上,描述响应类的属性

在这里插入图片描述

自定义对应Map参数的注解

由于原生的对于Map参数的注解,我在使用中一直没调试成功过,所以使用自定义注解的方式实现;

/**
 * @author akieay
 */
@Target({ElementType.PARAMETER, ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiJsonObject {

    /**
     * 对象属性值
     * @return
     */
    ApiJsonProperty[] value();

    /**
     * 对象名称
     * @return
     */
    String name();

}



/**
 * @author akieay
 */
@Target(ElementType.ANNOTATION_TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiJsonProperty {
    /**
     * key
     * @return
     */
    String key();

    String example() default "";

    /**
     * 支持string 和 int
     * @return
     */
    String type() default "string";

    String description() default "";

}


/**
 * @author akieay
 * plugin加载顺序,默认是最后加载
 */
@Component
@Order
public class MapApiReader implements ParameterBuilderPlugin {
    @Autowired
    private TypeResolver typeResolver;

    @Override
    public void apply(ParameterContext parameterContext) {
        ResolvedMethodParameter methodParameter = parameterContext.resolvedMethodParameter();

        //判断是否需要修改对象ModelRef,这里我判断的是Map类型和String类型需要重新修改ModelRef对象
        if (methodParameter.getParameterType().canCreateSubtype(Map.class) || methodParameter.getParameterType().canCreateSubtype(String.class)) {
            //根据参数上的ApiJsonObject注解中的参数动态生成Class
            Optional<ApiJsonObject> optional = methodParameter.findAnnotation(ApiJsonObject.class);
            if (optional.isPresent()) {
                //model 名称
                String name = optional.get().name();
                ApiJsonProperty[] properties = optional.get().value();

                //像documentContext的Models中添加我们新生成的Class
                parameterContext.getDocumentationContext().getAdditionalModels().add(typeResolver.resolve(createRefModel(properties, name)));

                //修改Map参数的ModelRef为我们动态生成的class
                parameterContext.parameterBuilder()
                        .parameterType("body")
                        .modelRef(new ModelRef(name))
                        .name(name);
            }
        }

    }

    /**
     * 动态生成的Class 所在包
     */
    private final static String basePackage = "com.*.*.*.swagger.model.";

    /**
     * 根据propertys中的值动态生成含有Swagger注解的javaBeen
     */
    private Class createRefModel(ApiJsonProperty[] propertys, String name) {
        ClassPool pool = ClassPool.getDefault();
        CtClass ctClass = pool.makeClass(basePackage + name);

        try {
            for (ApiJsonProperty property : propertys) {
                ctClass.addField(createField(property, ctClass));
            }
            return ctClass.toClass();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据property的值生成含有swagger apiModelProperty注解的属性
     */
    private CtField createField(ApiJsonProperty property, CtClass ctClass) throws NotFoundException, CannotCompileException {
        CtField ctField = new CtField(getFieldType(property.type()), property.key(), ctClass);
        ctField.setModifiers(Modifier.PUBLIC);

        ConstPool constPool = ctClass.getClassFile().getConstPool();

        AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
        Annotation ann = new Annotation("io.swagger.annotations.ApiModelProperty", constPool);
        ann.addMemberValue("value", new StringMemberValue(property.description(), constPool));
        ann.addMemberValue("example", new StringMemberValue(property.example(), constPool));

        attr.addAnnotation(ann);
        ctField.getFieldInfo().addAttribute(attr);

        return ctField;
    }

    private CtClass getFieldType(String type) throws NotFoundException {
        CtClass fileType = null;
        switch (type) {
            case "string":
                fileType = ClassPool.getDefault().get(String.class.getName());
                break;
            case "int":
                fileType = ClassPool.getDefault().get(Integer.class.getName());
                break;
        }
        return fileType;
    }

    @Override
    public boolean supports(DocumentationType delimiter) {
        return true;
    }
}

在这里插入图片描述
效果展示:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值