SpringMvc+Swagger2整合

本文介绍如何在SpringMvc项目中快速整合Swagger2,通过3步实现API文档自动生成。包括添加依赖、配置类及启动项目,最后访问Swagger界面查看效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringMvc+Swagger2整合

一、准备工作

正常可运行Controller的WEB项目

二、添加代码如下,只需3步

  1. POM
<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>
  1. 增加类,放在项目中
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.xxx.controller")//controller的包路径
@EnableSwagger2
public class Swagger2 {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.xxx.controller"))
                // .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("xxxx系统 APIs")
                .description("")
                .termsOfServiceUrl("")
                .version("1.0")
                .build();
    }

}
  1. mvc-xml中增加(直接copy,不需要修改)
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/><!--必须-->
    <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/><!--必须-->

三、启动

http://localhost:8080/swagger-ui.html
如果配置了项目名称,则
http://localhost:8080/xxxx/swagger-ui.html

swagger2页面

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值