美文网首页
SpringBoot集成Swagger

SpringBoot集成Swagger

作者: 你慧快乐 | 来源:发表于2018-09-06 15:47 被阅读0次

    swagger与Spring boot程序配合组织出强大RESTful API文档。它既可以减少我们创建文档的工作量,同时说明内容又整合入实现代码中,让维护文档和修改代码整合为一体,可以让我们在修改代码逻辑的同时方便的修改文档说明。

    第一步:引入swagger的依赖文件:

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

    这里的版本为2.7.0。

    第二步:新建SwaggerProperties属性文件:

    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.stereotype.Component;
    
    /**
     * @author guotx
     * @create 2018-04-27 14:42
     * @desc 配置swagger信息
     **/
    @Component
    @PropertySource(value = "classpath:application.properties")
    @ConfigurationProperties(prefix = "swagger")
    public class SwaggerProperties {
    
        private String basePackage;
        private String title;
        private String contactName;
        private String contactEmail;
        private String license;
        private String licenseUrl;
        private String termsOfServiceUrl;
        private String version;
        private String desc;
    (省略getter和setter方法)
    }
    

    第三步:新建SwaggerConfig配置文件:

    
    import com.alibaba.rhino.fileupload.oss.OSSFile;
    
    import com.fasterxml.classmate.TypeResolver;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.multipart.MultipartFile;
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.schema.AlternateTypeRule;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.service.Contact;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    
    /**
     * @author guotx
     * @create 2018-04-27 14:31
     * @desc Swagger接口配置
     **/
    @Configuration
    public class SwaggerConfig {
        @Autowired
        private SwaggerProperties swaggerProperties;
    
        @Value("${spring.profiles.active}")
        String env;
    
        private final static String CAN_SHOW_ENV_PROFILES = "testing;project;staging";
        @Bean
        public Docket createRestApi() {
            TypeResolver resolver = new TypeResolver();
            AlternateTypeRule alternateTypeRule = new AlternateTypeRule(resolver.resolve(OSSFile.class),
                resolver.resolve(MultipartFile.class));
            return new Docket(DocumentationType.SWAGGER_2)
                .enable(CAN_SHOW_ENV_PROFILES.contains(env))
                .apiInfo(apiInfo())
                .alternateTypeRules(alternateTypeRule)
                .select().apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
                .paths(PathSelectors.any())
                .build();
        }
    
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                .title(swaggerProperties.getTitle())
                .description(swaggerProperties.getDesc())
                .termsOfServiceUrl("")
                .contact(new Contact(swaggerProperties.getContactName(), null, swaggerProperties.getContactEmail()))
                .license(swaggerProperties.getLicense())
                .licenseUrl(swaggerProperties.getLicenseUrl())
                .termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl())
                .version(swaggerProperties.getVersion())
                .build();
        }
    }
    

    第四步:application.properties添加配置信息

    #接口文档配置
    swagger.basePackage=com.tx.house.controller
    swagger.title=房屋管理系统
    swagger.desc=房屋管理接口
    swagger.version=1.0
    swagger.contactName=guotx、Lili
    swagger.contactEmail=
    swagger.license=
    swagger.licenseUrl=
    swagger.termsOfServiceUrl= https://www.jianshu.com
    

    第五步:Controller中使用

    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiImplicitParam;
    import io.swagger.annotations.ApiImplicitParams;
    import io.swagger.annotations.ApiOperation;
    
    @Api(value = "XXX业务接口", tags = { "XXX业务接口" }, hidden = true)
    @RestController
    @RequestMapping(value = "api/order")
    public class OrderController {
    @ApiOperation(value = "XXX接口描述")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "id", defaultValue = "278002", value = "订单ID", required = true, dataType = "Long", paramType = "query"),
                @ApiImplicitParam(name = "buyerId", defaultValue = "3736416120", value = "买家ID", required = true, dataType = "Long", paramType = "query") })
        @GetMapping(value = "/detail")
        public PojoResult<OrderDetailVO> detail(@RequestParam("id") Long id, @RequestParam("buyerId") Long buyerId) {
      ......
      }
    }
    
    • 后记
      参数列表实现可选效果,只需在@ApiImplicitParam注解里面加上allowableValues="选项1,选项2,选项3,……"即可,多选也很简单,加上allowMultiple = true。
    @ApiOperation(value = "测试swagger下拉框")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "类型", dataType = "String", paramType = "query",
                    allowableValues = "苹果,荔枝,菠萝", allowMultiple = true)
    })
    @RequestMapping(value = "/select", method = {RequestMethod.GET})
    public String[] mystyle(String[] type) {
        return type;
    }
    

    springfox-swagger2版本的问题,2.5.x - 2.7.x 版本支持多选,2.8.0版本后不支持下拉框多选。

    相关文章

      网友评论

          本文标题:SpringBoot集成Swagger

          本文链接:https://www.haomeiwen.com/subject/louxgftx.html