博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring boot 使用swagger
阅读量:5891 次
发布时间:2019-06-19

本文共 8597 字,大约阅读时间需要 28 分钟。

在pom.xml中添加maven依赖

io.springfox
springfox-swagger2
2.7.0
io.springfox
springfox-swagger-ui
2.7.0

刚开始我用的2.8.0版本,后来折腾了好久,swagger页面就是不出来。换成2.7.0就好了。也许你折腾半天,换个版本就好了。

添加Swagger配置类:

package com.test.configuration;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import io.swagger.annotations.ApiOperation;import springfox.documentation.builders.ApiInfoBuilder;import springfox.documentation.builders.PathSelectors;import springfox.documentation.builders.RequestHandlerSelectors;import springfox.documentation.service.ApiInfo;import springfox.documentation.spi.DocumentationType;import springfox.documentation.spring.web.plugins.Docket;import springfox.documentation.swagger2.annotations.EnableSwagger2;/***Swagger2配置类*/@Configuration@EnableSwagger2//启用Swagger2public class Swaggers {        @Bean    public Docket createRestApi(){        return new Docket(DocumentationType.SWAGGER_2)        .apiInfo(apiInfo())        .select()        .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))//扫描所有有注解的api        .paths(PathSelectors.any())        .build();    }        /**     * 首页描述     * @return    */    private ApiInfo apiInfo(){        return new ApiInfoBuilder()        .title("电话外呼api文档")        .description("rest接口")        .build();    }}

 

添加controller类

package com.text.crm.callout.controller;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import org.springframework.beans.factory.annotation.Autowired;import com.text.callout.model.WarnCallOut;import com.text.callout.service.WarnCallOutService;@RestController@RequestMapping("/warn")@Api(tags="电话外呼信息保存接口")public class WarnCallOutController{    @Autowired    private WarnCallOutService warnCallOutService;        /**    *@param WarnCallOut电话外呼对象    *@return    */    @ApiOperation("保存电话外呼信息")    @RequestMapping(value = "/add",method=RequestMethod.POST)    public String addWarnCallOut(WarnCallOut warnCallOut){        return warnCallOutService.addWarnCallOut(warnCallOut);    }}

 添加POJO类

package com.test.entity;import io.swagger.annotations.ApiModel;import io.swagger.annotations.ApiModelProperty;@ApiModel("电话外呼对象")public class WarnCallOut {    @ApiModelProperty(value="序号,从1开始",hidden=true)    private Long id;    @ApiModelProperty(value="姓名",required=true)    private String name;    @ApiModelProperty(value="需要外乎的号码,本地号码加9,外地号码加90,多个号码用|隔开,如913800000000|9013900000000",required=true)    private String phonenum;    @ApiModelProperty(value="操作时间,如2018-12-06 22:00:00",required=true)    private String requesttime;        public Long getId() {        return id;    }    public void setId(Long id) {        this.id = id;    }        public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getPhonenum() {        return phonenum;    }    public void setPhonenum(String phonenum) {        this.phonenum = phonenum;    }    public String getRequesttime() {        return requesttime;    }    public void setRequesttime(String requesttime) {        this.requesttime = requesttime;    }}

运行启动类,启动Spring Boot程序,访问:

 

 

 

如果你的没有成功。可以试试把配置类改成如下:

package com.test.configuration;import io.swagger.annotations.ApiOperation;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.util.UriComponentsBuilder;import springfox.documentation.builders.ApiInfoBuilder;import springfox.documentation.builders.PathSelectors;import springfox.documentation.builders.RequestHandlerSelectors;import springfox.documentation.service.ApiInfo;import springfox.documentation.spi.DocumentationType;import springfox.documentation.spring.web.plugins.Docket;import springfox.documentation.spring.web.paths.Paths;import springfox.documentation.spring.web.paths.AbstractPathProvider;import springfox.documentation.swagger2.annotations.EnableSwagger2;import java.util.List;import org.springframework.web.servlet.config.annotation.*;import org.springframework.format.FormatterRegistry;import org.springframework.http.converter.HttpMessageConverter;import org.springframework.validation.MessageCodesResolver;import org.springframework.validation.Validator;import org.springframework.web.method.support.HandlerMethodArgumentResolver;import org.springframework.web.method.support.HandlerMethodReturnValueHandler;import org.springframework.web.servlet.HandlerExceptionResolver;import org.springframework.web.context.request.async.DeferredResult;/***Swagger2配置类*/@Configuration@EnableSwagger2//启用Swagger2,生产环境记得注释掉public class Swaggers implements WebMvcConfigurer{        @Bean    public Docket createRestApi(){        return new Docket(DocumentationType.SWAGGER_2)        .apiInfo(apiInfo())        .select()        .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))//扫描所有有注解的api        .paths(PathSelectors.any())        .build();    }        /**     * 首页描述     * @return    */    private ApiInfo apiInfo(){        return new ApiInfoBuilder()        .title("电话外呼api文档")        .description("rest接口")        .build();    }        /**     *重写BASE URL    */    class BasePathAwareRalativePathProvider extends AbstractPathProvider{        private String basePath;                public BasePathAwareRalativePathProvider(String basePath){            this.basePath=basePath;        }                @Override        protected String applicationPath(){            return basePath;        }                @Override        protected String getDocumentationPath(){            return "/";        }                @Override        public String getOperationPath(String OperationPath){            UriComponentsBuilder uriComponentsBuilder=UriComponentsBuilder.fromPath("/");            return Paths.removeAdjacentForwardSlashes(uriComponentsBuilder.path("").build().toString());        }    }        @Override    public void addResourceHandlers(ResourceHandlerRegistry registry){        registry.addResourceHandler("swagger-ui.html")                .addResourceLocations("classpath:/META-INF/resources/");        registry.addResourceHandler("/webjars/**")                .addResourceLocations("classpath:/META-INF/resources/webjars/");    };        /**     * 跨域支持     * @param corsRegistry    */    @Override    public void addCorsMappings(CorsRegistry corsRegistry){                corsRegistry.addMapping("/**")                .allowedOrigins("*")                .allowCredentials(true)                .allowedMethods("GET","POST","PUT","DELETE")                .allowedHeaders("*");    }                @Override    public void configurePathMatch(PathMatchConfigurer pathMatchConfigurer){}    @Override    public void configureContentNegotiation(ContentNegotiationConfigurer contentNegotiationConfigurer){}    @Override    public void configureAsyncSupport(AsyncSupportConfigurer asyncSupportConfigurer){};    @Override    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer defaultServletHandlerConfigurer){};    @Override    public void addFormatters(FormatterRegistry formatterRegistry){};    @Override    public void addInterceptors(InterceptorRegistry interceptorRegistry){};    @Override    public void addViewControllers(ViewControllerRegistry viewControllerRegistry){};    @Override    public void configureViewResolvers(ViewResolverRegistry viewResolverRegistry){};    @Override    public void addArgumentResolvers(List
argumentResolvers){}; @Override public void addReturnValueHandlers(List
returnValueHandlers){}; @Override public void configureMessageConverters(List
> converters){}; @Override public void extendMessageConverters(List
> converters){}; @Override public void configureHandlerExceptionResolvers(List
exceptionResolvers){}; @Override public void extendHandlerExceptionResolvers(List
exceptionResolvers){}; @Override public Validator getValidator(){ return null; } @Override public MessageCodesResolver getMessageCodesResolver(){ return null; } }

还是不行的话,

请下载这个demo :         下载好解压然后eclipse导入MAVEN项目  直接就能运行。

转载于:https://www.cnblogs.com/Alwaysbecoding/p/10077508.html

你可能感兴趣的文章
在Fedora8上安装MySQL5.0.45的过程
查看>>
设计模式之命令模式
查看>>
android 测试 mondey
查看>>
Spring AOP项目应用——方法入参校验 & 日志横切
查看>>
使用REST-Assured对API接口进行自动化测试
查看>>
王潮歌跨界指导HUAWEI P20系列发布会 颠覆传统 眼界大开!
查看>>
王高飞:微博已收购一直播 明年一季度重点是功能与流量打通
查看>>
趣头条发行区间7至9美元 预计9月14日美国上市
查看>>
新北市长侯友宜:两岸交流应从隔壁最亲近的人开始
查看>>
全面屏的Nokia X即将上线,不到2000元的信仰你要充值吗?
查看>>
HTML5音频audio属性
查看>>
ES6学习
查看>>
Centos7搭建Django环境
查看>>
序列化一个Intent
查看>>
JavaScript数据类型及语言基础--ife
查看>>
进阶 Nginx 高手必须跨越的 5 座大山
查看>>
部署P2P升级的脚本
查看>>
jenkins--ant持续集成测试build文件脚本 测试报告
查看>>
ubuntu下安装libxml2
查看>>
nginx_lua_waf安装测试
查看>>