springboot-自动生成前后端接口文档

1,384 阅读1分钟

背景

前后端文档的编写和维护,很费时间,有没有办法自动生成?即根据源码自动生成。

可以。

引入框架swagger

引入依赖

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

指定哪些类是接口

package com.wz.bpm.doc;

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

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

/**
 * 自动生成前后端接口文档
 * @author gongzhihao
 *
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.wz.bpm.controller")) //指定控制器controller的包,包下面的所有类和方法,都会自动生成接口
                .paths(PathSelectors.any())
                .build().apiInfo(new ApiInfoBuilder()
                        .title("SpringBoot整合Swagger")
                        .description("SpringBoot整合Swagger,详细信息......")
                        .version("9.0")
                        .contact(new Contact("啊啊啊啊","blog.csdn.net","aaa@gmail.com"))
                        .license("The Apache License")
                        .licenseUrl("http://www.baidu.com")
                        .build());
    }
}

spring security

如果使用了安全框架,去掉对swagger本身的请求路径的拦截。

@Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/index.html", "/static/**", "/login_p", "/login_p2","/favicon.ico","/","/gzh","/department")
        
        .antMatchers("/swagger-ui.html") //这些都是swagger的请求路径,全部不拦截
        .antMatchers("/v2/**")
        .antMatchers("/swagger-resources/**")
        .antMatchers("/webjars/**")
        .antMatchers("/csrf")
        
        .antMatchers("/employee/**");
       
    }

如何访问?

http://localhost:8083/swagger-ui.html

evernotecid://07CE98CA-5C19-40B7-98FF-26C9B38E33B5/appyinxiangcom/21584510/ENResource/p56

参考

blog.csdn.net/u012702547/… //江南一点雨,简单易懂

juejin.cn/post/684490…

my.oschina.net/u/3362894/b…