ssm整合思路与配置详解_接口整合配置

ssm整合思路与配置详解_接口整合配置swagger2于17年停止维护,现在最新的版本为17年发布的Swagger3(OpenApi3)

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全家桶1年46,售后保障稳定

swagger介绍

Swagger 是一套基于 OpenAPI 规范(OpenAPI Specification,OAS)构建的开源工具,后来成为了 Open API 标准的主要定义者。
对于 Rest API 来说很重要的一部分内容就是文档,Swagger 为我们提供了一套通过代码和注解自动生成文档的方法,这一点对于保证API 文档的及时性将有很大的帮助。

swagger2于17年停止维护,现在最新的版本为17年发布的 Swagger3(Open Api3)。

springfox介绍

SpringFox是 spring 社区维护的一个项目(非官方)
由于Spring的流行,Marty Pitt编写了一个基于Spring的组件swagger-springmvc,用于将swagger集成到springmvc中来,而springfox则是从这个组件发展而来。

springfox-swagger 2

SpringBoot项目整合swagger2需要用到两个依赖:springfox-swagger2springfox-swagger-ui,用于自动生成swagger文档。

  • springfox-swagger2:这个组件的功能用于帮助我们自动生成描述API的json文件
  • springfox-swagger-ui:就是将描述API的json文件解析出来,用一种更友好的方式呈现出来。

SpringFox 3.0.0 发布

此版本的亮点:
  • Spring5,Webflux支持(仅支持请求映射,尚不支持功能端点)。
  • Spring Integration支持。
  • SpringBoot支持springfox Boot starter依赖性(零配置、自动配置支持)。
  • 支持OpenApi 3.0.3。
  • 零依赖。几乎只需要spring-plugin,swagger-core ,现有的swagger2注释将继续工作并丰富openapi3.0规范。
兼容性说明:
  • 需要Java 8
  • 需要Spring5.x(未在早期版本中测试)
  • 需要SpringBoot 2.2+(未在早期版本中测试)

swagger3.0 与2.xx配置差异:

  1. 应用主类添加注解@EnableOpenApi (swagger2是@EnableSwagger2)
  2. swagger配置类SwaggerProperties.class,与swagger2.xx 版本有差异,具体看下文
  3. 自定义一个配置类 SwaggerConfiguration.class,看下文
  4. 访问地址:http://localhost:8080/swagger-ui/index.html (swagger2.xx版本访问的地址为http://localhost:8080/swagger-ui.html)

整合使用完整过程

Maven项目中引入springfox-boot-starter依赖:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

Jetbrains全家桶1年46,售后保障稳定

application.yml配置

spring:
  application:
    name: springfox-swagger
server:
  port: 8080
# ===== 自定义swagger配置 ===== #
swagger:
  enable: true
  application-name: ${ 
   spring.application.name}
  application-version: 1.0
  application-description: springfox swagger 3.0整合Demo
  try-host: http://localhost:${server.port}

应用主类 Controller类

@EnableOpenApi // 也可以不写此注解
@Api(description="讲师管理")
@RestController
@RequestMapping("/admin/edu/teacher")

public class MyController { 
   

    @Autowired
    private TeacherService teacherService;
    
    @ApiOperation(value = "所有讲师列表")
    @GetMapping
    public List<Teacher> list(){ 
   
        return teacherService.list(null);
    }
    
    @ApiOperation(value = "根据ID删除讲师")
    @DeleteMapping("{id}")
    public boolean removeById(
            @ApiParam(name = "id", value = "讲师ID", required = true)
            @PathVariable String id){ 
   
        return teacherService.removeById(id);
    }
}

一些常用注解说明

@Api:用在controller类,描述API接口
@ApiOperation:描述接口方法
@ApiModel:描述对象
@ApiModelProperty:描述对象属性
@ApiImplicitParams:描述接口参数
@ApiResponses:描述接口响应
@ApiIgnore:忽略接口方法

自定义一个swagger配置类SwaggerProperties.class

@Component
@ConfigurationProperties("swagger")
public class SwaggerProperties { 
   
    /** * 是否开启swagger,生产环境一般关闭,所以这里定义一个变量 */
    private Boolean enable;
    
    /** * 项目应用名 */
    private String applicationName;

    /** * 项目版本信息 */
    private String applicationVersion;

    /** * 项目描述信息 */
    private String applicationDescription;

    /** * 接口调试地址 */
    private String tryHost;

    public Boolean getEnable() { 
   
        return enable;
    }

    public void setEnable(Boolean enable) { 
   
        this.enable = enable;
    }

    public String getApplicationName() { 
   
        return applicationName;
    }

    public void setApplicationName(String applicationName) { 
   
        this.applicationName = applicationName;
    }

    public String getApplicationVersion() { 
   
        return applicationVersion;
    }

    public void setApplicationVersion(String applicationVersion) { 
   
        this.applicationVersion = applicationVersion;
    }

    public String getApplicationDescription() { 
   
        return applicationDescription;
    }

    public void setApplicationDescription(String applicationDescription) { 
   
        this.applicationDescription = applicationDescription;
    }

    public String getTryHost() { 
   
        return tryHost;
    }

    public void setTryHost(String tryHost) { 
   
        this.tryHost = tryHost;
    }
}

springfox swagger3配置类SwaggerConfiguration.class

import io.swagger.models.auth.In;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.springframework.boot.SpringBootVersion;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import java.lang.reflect.Field;
import java.util.*;

@Configuration
public class SwaggerConfiguration implements WebMvcConfigurer { 
   
    private final SwaggerProperties swaggerProperties;

    public SwaggerConfiguration(SwaggerProperties swaggerProperties) { 
   
        this.swaggerProperties = swaggerProperties;
    }

    @Bean
    public Docket createRestApi() { 
   
        return new Docket(DocumentationType.OAS_30).pathMapping("/")

                // 定义是否开启swagger,false为关闭,可以通过变量控制
                .enable(swaggerProperties.getEnable())

                // 将api的元信息设置为包含在json ResourceListing响应中。 
                .apiInfo(apiInfo())

                // 接口调试地址
                .host(swaggerProperties.getTryHost())

                // 选择哪些接口作为swagger的doc发布
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()

                // 支持的通讯协议集合
                .protocols(newHashSet("https", "http"))

                // 授权信息设置,必要的header token等认证信息
                .securitySchemes(securitySchemes())

                // 授权信息全局应用
                .securityContexts(securityContexts());
    }

    /** * API 页面上半部分展示信息 */
    private ApiInfo apiInfo() { 
   
        return new ApiInfoBuilder().title(swaggerProperties.getApplicationName() + " Api Doc")
                .description(swaggerProperties.getApplicationDescription())
                .contact(new Contact("lighter", null, "123456@gmail.com"))
                .version("Application Version: " + swaggerProperties.getApplicationVersion() + ", Spring Boot Version: " + SpringBootVersion.getVersion())
                .build();
    }

    /** * 设置授权信息 */
    private List<SecurityScheme> securitySchemes() { 
   
        ApiKey apiKey = new ApiKey("BASE_TOKEN", "token", In.HEADER.toValue());
        return Collections.singletonList(apiKey);
    }

    /** * 授权信息全局应用 */
    private List<SecurityContext> securityContexts() { 
   
        return Collections.singletonList(
                SecurityContext.builder()
                        .securityReferences(Collections.singletonList(new SecurityReference("BASE_TOKEN", new AuthorizationScope[]{ 
   new AuthorizationScope("global", "")})))
                        .build()
        );
    }

    @SafeVarargs
    private final <T> Set<T> newHashSet(T... ts) { 
   
        if (ts.length > 0) { 
   
            return new LinkedHashSet<>(Arrays.asList(ts));
        }
        return null;
    }

    /** * 通用拦截器排除swagger设置,所有拦截器都会自动加swagger相关的资源排除信息 */
    @SuppressWarnings("unchecked")
    @Override
    public void addInterceptors(InterceptorRegistry registry) { 
   
        try { 
   
            Field registrationsField = FieldUtils.getField(InterceptorRegistry.class, "registrations", true);
            List<InterceptorRegistration> registrations = (List<InterceptorRegistration>) ReflectionUtils.getField(registrationsField, registry);
            if (registrations != null) { 
   
                for (InterceptorRegistration interceptorRegistration : registrations) { 
   
                    interceptorRegistration
                            .excludePathPatterns("/swagger**/**")
                            .excludePathPatterns("/webjars/**")
                            .excludePathPatterns("/v3/**")
                            .excludePathPatterns("/doc.html");
                }
            }
        } catch (Exception e) { 
   
            e.printStackTrace();
        }
    }

}

效果图:

在这里插入图片描述

扩展资料

swagger 官网:swagger.io(https://swagger.io/)
springfox 官网:springfox(http://springfox.github.io/springfox/)
springfox Github 仓库:springfox / springfox(https://github.com/springfox/springfox)
springfox-demos Github 仓库:springfox / springfox-demos(https://github.com/springfox/springfox-demos)
springfox Maven 仓库:Home » io.springfox(https://mvnrepository.com/artifact/io.springfox)


在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/226815.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 如何理解python报错信息_csb报错

    如何理解python报错信息_csb报错#软件版本python3.7pycharm2018.3.1遇到的问题解释及处理方法#1报错#TypeError:‘key’isaninvalidkeywordargumentforprint()代码:def_cmp(x,y):ifx&amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;y:return-1ifx&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;y:return

    2022年8月28日
    2
  • 【知识小结】Git 个人学习笔记及心得

    【知识小结】Git 个人学习笔记及心得

    2021年10月23日
    43
  • atm异步传输模式特性_ATM是什么模式

    atm异步传输模式特性_ATM是什么模式AsynchronousTransferMode.  ATM是一种传输模式,在这一模式中,信息被组织成信元,因包含来自某用户信息的各个信元不需要周期性出现,这种传输模式是异步的。   ATM是网络新技术,它采用基于信元的异步传输模式和虚电路结构,根本上解决了多媒体的实时性及带宽问题。实现面向虚链路的点到点传输,它通常提供155Mbps的带宽。它既汲取了话务通讯中电路交换的“有连接”服务

    2022年9月21日
    3
  • 毕业六年

    今年工作变化。这一年可以说命途多舛,下半年短短几个月,换了3条业务4个老板,有被动调整,也有主动转岗,面临比较重要的选择,还是相当煎熬的。这个过程有些坑,空了单独分享。运气不好的是频繁拥抱变化,有些努力白费了,意外之中又有意外,不过运气好的是年终没吃太多亏,权当是走个弯路,浪费了一年时间吧。惰性。技术上来说,转后端一年多,工作够用了,不过这两年从客户端折腾到前端又到后端,把技术热情磨没了,可能也是各方面原因,今年第一次感觉到了惰性,有点佛,感觉够用就行,不再试图知其所以然…

    2022年3月11日
    48
  • 数据库建立索引常用的规则

    数据库建立索引常用的规则数据库建立索引常用的规则如下:1、表的主键、外键必须有索引; 2、数据量…

    2022年7月24日
    13
  • c语言 背包算法,c语言背包问题(背包最大容量c语言算法)[通俗易懂]

    c语言 背包算法,c语言背包问题(背包最大容量c语言算法)[通俗易懂]求旅行者能获得的最大总价值。请用C语言编程下面是核心的代码(递归函数的代码)别的由你自己搞掂啦(在main函数中的实现,输入,输出的格式)s为一个背包可以放入的物品总重量.n为物品数,w[n]为物品重量.背包问题#includeintmax(intx,inty){if(x>=y)returnx;elsereturny;}intf(int*m,。1在代码风格上…

    2022年7月14日
    37

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号