• spring boot 使用swagger


    在pom.xml中添加maven依赖

    <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>

    刚开始我用的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//启用Swagger2
    public 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程序,访问:http://localhost:8080/swagger-ui.html

     

     

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

    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<HandlerMethodArgumentResolver> argumentResolvers){};
        @Override
        public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers){};
        @Override
        public void configureMessageConverters(List<HttpMessageConverter<?>> converters){};
        @Override
        public void extendMessageConverters(List<HttpMessageConverter<?>> converters){};
        @Override
        public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers){};
        @Override
        public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers){};
        @Override
        public Validator getValidator(){
            return null;
        }
        @Override
        public MessageCodesResolver getMessageCodesResolver(){
            return null;
        }        
    }

    还是不行的话,

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

    spring boot 启动jar包时可指定Xmx(jvm运行过程中分配的最大内存),Xms(jvm启动时分配的内存)

    java -jar -Xmx 2048m -Xms 2048m 项目名.jar

    -----------------------------------------------------------------------------
  • 相关阅读:
    串口速率问题
    java中byte short int的理解
    matlab 设置坐标轴的有效数字
    Tomcat闪退
    解决linux下sudo更改文件权限报错xxxis not in the sudoers file. This incident will be reported.
    Git的常用命令
    [原创]创建指定RowState属性的DataRow实例
    [转]中文VS2008中安装ASP.NET MVC框架出现问题的解决方法
    [转]JavaScript为事件处理器传递参数
    [转]LINQ to SQL(LINQ2SQL) vs. ADO.NET Entity Framework
  • 原文地址:https://www.cnblogs.com/Alwaysbecoding/p/10077508.html
Copyright © 2020-2023  润新知