SpringMvc 集成swagger2

本文介绍如何在SpringMVC项目中集成Swagger2以生成在线API文档。通过添加依赖、配置SwaggerConfig类及修改spring-mvc.xml文件,可以实现API文档自动生成。最后,在Controller上添加@API注解完成集成。

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

SpringMvc 集成swagger2

 

最开始是在Ibase4J开源项目中得知的swagger开源在线api测试文档。觉得还可以就使用到项目中了。一下是整合步骤:(本项目集成基于Maven Springmvc环境)

1、添加pom.xml增加依赖包:

<!-- swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>

<!-- json -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.6.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.6.5</version>
</dependency>
</dependencies>

 

2、在项目中添加swagger的配置文件SwaggerConfig.java

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }

}

 

3、在项目的spring-mvc.xmlspring配置文件中添加第二步的配置文件,并重新指定 

 Swagger资源重定向(仅作为后台使用不提供静态资源):

<!--Swagger  -->
 //com.xmsrs.hengyun.api替换为SwaggerConfig在的包路径
<context:component-scanbase-package="com.xmsrs.hengyun.api"/>
 //class 替换为你项目中SwaggerConfig的实际路径
<beanclass="com.xmsrs.hengyun.api.modules.utils.SwaggerConfig"/>

<!--Swagger资源重定向(仅作为后台使用不提供静态资源) -->
<mvc:resourceslocation="classpath:/META-INF/resources/"mapping="swagger-ui.html"/>
<mvc:resourceslocation="classpath:/META-INF/resources/webjars/"mapping="/webjars/**"/>


4、在项目的Controller中加上@API注解,具体的注解请参考swagger官网:http://swagger.io/



5、浏览器输入:http://localhost:8080/swagger-ui.html#/进行访问,查看是否配置成功。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值