Spring-MVC 结合 Swagger2

目录

一、引入依赖

二、创建Swagger配置类

三、修改Spring-MVC配置文件

四、在游览器打开

五、配置 Swagger

六、使用 Swagger 

七、Swagger 的常用注解

@ApiOperation() 

@ApiModel ()、@ApiModelProperty ()


一、引入依赖

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>

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

        <!--Swagger 需要用到这个依赖-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>    
            <version>2.13.4.1</version>
        </dependency>

二、创建Swagger配置类

三、修改Spring-MVC配置文件

    <!--开启包扫描路径-->
    <context:component-scan base-package="com.shao"/>

    <!-- 开启注解驱动-->
    <mvc:annotation-driven />

    <!-- 映射 Swagger-ui 静态资源-->
    <mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
    <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>

四、在游览器打开

http://localhost:8090/项目名/swagger-ui.html

五、配置 Swagger

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    //配置Swagger的Docket的bean实例
    @Bean
    public Docket docket() {
        // 创建一个Docket实例并指定文档类型为Swagger 2
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())     // 设置API的基本信息,如标题、描述等
                .select()               // 选择扫描哪些包
                .apis(RequestHandlerSelectors.basePackage("com.xxx"))
                .paths(PathSelectors.any())     // 选择扫描哪些路径下的接口
                .build();                       // 构建 Docket
    }

    // 配置 Swagger 信息
    public ApiInfo apiInfo(){
        return new ApiInfo("Swagger"    // 标签
                , "这是 接口文档"        // 描述
                , "v1.0"
                , "https://www.baidu.com"
                , new Contact("张三", "https://www.baidu.com", "")    // 作者信息
                , "Apache 2.0"
                , "http://www.apache.org/licenses/LICENSE-2.0"
                , new ArrayList());
    }
}

打开接口详情,可以看到有很多类型的请求方法,这是因为 我们使用的是 @RequestMapping() 注解 ,改成具体的对应的 注解 就可以了

POST 请求方法  改成 @PostMapping () 注解 

 

这样就清爽多啦

六、使用 Swagger 

 

发送请求

测试成功

七、Swagger 的常用注解

@ApiOperation() 

用于描述接口信息

@ApiModel ()、@ApiModelProperty ()

@ApiModel ()                对模型类做注解,实体类

@ApiModelProperty ()        对属性做注解

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值