Spring4集成Swagger:真的只需要四步,五分钟速成

https://blog.csdn.net/BlackMambaProgrammer/article/details/72354007

  • 如果你所在的公司的还没有使用swagger甚至没有听说过swagger,赶快学习一下我的这篇博客吧,五分钟速成,傻瓜式的集成,但就是这么简单的应用一定会让他们震惊到的。
  • 首先对swagger做一个简介吧:swagger是后台开发的神器,也是前后端交流的渠道。你可以用swagger做什么?首先,你以后基本可以告别单元测试了;其次,你不用再写接口文档了,也不需要写完之后再去对文档进行维护了。swagger可以完全模拟http请求,入参出参和实际情况差别几乎为零。说了这些,直接来干货吧!
  • 集成四部曲: 
    • 第一步:导入两个依赖吧,如果你不是maven项目,那你去找找jar包吧,记住只需要两个,我看别的教程引入了七八个,简直是浪费。
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.6.1</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.6.1</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 第二步:添加一个类(拷贝下面的即可,注意修改包名,地址)
/**
 * Swagger配置
 *
 * @author wq
 * @since 2017-05-16
 */
@EnableWebMvc
@EnableSwagger2
@Configuration
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.z*.b*.c*.controller")) // 注意修改此处的包名
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("接口列表 v1.1.0") // 任意,请稍微规范点
                .description("接口测试") // 任意,请稍微规范点
                .termsOfServiceUrl("http://url/swagger-ui.html") // 将“url”换成自己的ip:port
                .contact("laowu") // 无所谓(这里是作者的别称)
                .version("1.1.0")
                .build();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 第三步:在mvc的配置的文件中添加下面配置,可能你的文件也许是叫 dispatcher.xml!(照抄即可,完全不需要修改)
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
       <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
  • 1
  • 2
  • 第四步:在方法和参数上添加注解
方法上:
@ApiOperation(value = "教程", httpMethod = "POST", notes = "教程")
放在入参中:
@ApiParam(required = true, name = "test", value = "教程入参") 
  • 1
  • 2
  • 3
  • 4

担心有些朋友还不太明白,放张图吧! 
这里写图片描述 
- 第五步:启动服务,然后在浏览器输入:

http://ip:port/swagger-ui.html
  • 1

出现下面的画面就代表大功告成: 
这里写图片描述
注意事项:如果你的项目中使用了拦截器,请将swagger资源放行(还是可以直接拷贝下面的配置,全部,不要怀疑v2)

<mvc:exclude-mapping path="/swagger*/**"></mvc:exclude-mapping>
<mvc:exclude-mapping path="/v2/**"></mvc:exclude-mapping>
<mvc:exclude-mapping path="/webjars/**"></mvc:exclude-mapping>
  • 1
  • 2
  • 3
版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/BlackMambaProgrammer/article/details/72354007

猜你喜欢

转载自blog.csdn.net/liyanlei5858/article/details/80326995