chen888的gravatar头像
chen888 2017-09-11 16:18:14

Spring MVC整合Swagger2的api文档实例

准备工作:jkd1.8、Tomcat7.0、eclipse、mysql数据库、maven环境

集成后的效果图:

Spring MVC整合Swagger2的api文档实例

spring MVC 集成Swagger2 的主要配置:

spring-mvc.xml下添加:

<!-- Swagger集合 -->
    <mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html" />
    <mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**" />

SwaggerConfig类:

Swagger2自定义配置:

@Configuration

@EnableWebMvc // 支持springmvc
@EnableSwagger2
@Component
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
            .apis(RequestHandlerSelectors.basePackage("com.chen.controller"))
            // 扫描所有有注解的api
            .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).paths(PathSelectors.any()).build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("RESTful APIs").description("Spring+MVC集合Swagger2的API。")
            .termsOfServiceUrl("http://localhost:8080").version("1.0.0").build();
    }
}

效果图:

Spring MVC整合Swagger2的api文档实例

最原始或者最简单的配置:

@Configuration
@EnableWebMvc
@EnableSwagger2
@ComponentScan(basePackages ={"com.chen.controller"})
public class SwaggerConfig {

  /**
   * Every Docket bean is picked up by the swagger-mvc framework - allowing for multiple
   * swagger groups i.e. same code base multiple swagger resource listings.
   */
  @Bean
  public Docket customDocket() {
      return new Docket(DocumentationType.SWAGGER_2);
  }
  
}

Spring MVC整合Swagger2的api文档实例

 

项目结构:

Spring MVC整合Swagger2的api文档实例

 

引用的jar包

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

Swagger2的注解自己上官网查。

 

搭建好运行环境,下载项目是可以直接运行的。

运行起来的访问路径是:

http://localhost:8080/information/swagger-ui.html#/

http://localhost:Tomcat端口/项目名称/swagger-ui.html#/

效果图如上面所展示。


打赏

已有4人打赏

wewelwell的gravatar头像 最代码官方的gravatar头像 最代码客服的gravatar头像 已注销用户的gravatar头像

文件名:information.zip,文件大小:37.514K 下载
最代码最近下载分享源代码列表最近下载
血羽如风  LV4 1月23日
lironggang  LV38 2021年9月22日
yuanchuang  LV22 2021年8月12日
开心灬愉悦  LV9 2021年5月2日
林志勇  LV10 2021年3月9日
雨沐风  LV2 2021年1月16日
heqian  LV16 2020年10月9日
青春的尾巴  LV3 2020年8月2日
zhuchuanhu2  LV3 2020年2月19日
zcl02036716  LV17 2019年12月19日
最代码最近浏览分享源代码列表最近浏览
血羽如风  LV4 1月23日
林间听风  LV10 2023年8月1日
843108982  LV1 2023年1月28日
yongjava21  LV26 2022年9月28日
1234mama  LV19 2022年3月22日
lironggang  LV38 2021年9月22日
yuanchuang  LV22 2021年8月12日
ls2008  LV15 2021年7月13日
chunqiu  LV5 2021年6月10日
开心灬愉悦  LV9 2021年5月2日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友