springmvc+swagger2

2018-01-17  本文已影响0人  SiLiangfeng

笔者最近拿springmvc4.x+swagger 2.8(最新版本)集成过程中碰到一些问题,现在分享一下

1、引入的包
swagger2 的包 maven仓库上找的最新版

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

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

2、如果启动有报jackjson的错,请再引入jackjson的包

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.6.6</version>
    </dependency>

3、我看过很多版本的集成,有些是不引入swagger-ui包,那么你就需要去自己下载swagger-ui 然后把 dist目录下的文件全部拷贝到自己的静态资源下。
我们需要把swagger的访问配置下静态路径
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>

4、项目里配置swagger

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @Author zhangwenfeng
 * @Date 2018/1/17
 * @Description
 */
@EnableWebMvc
@EnableSwagger2
@Configuration
public class RestApiConfig extends WebMvcConfigurationSupport {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("cn.zx.user.controller.api"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("用户中心api")
                .termsOfServiceUrl("www.baidu.com")
                .contact("xxxx")
                .version("1.1")
                .build();
    }
}

5、最后一个注意点,如果使用的是 fastjson 请把版本升级到1.2.15以上。

6、使用 swagger-ui包的 访问路径为 http://{ip}:{port}:{project}/swagger-ui.html

7、在被扫描的controller里 加swagger注解,具体注解使用方式自行百度.

上一篇下一篇

猜你喜欢

热点阅读