SPringBoot整合Swagger2

Swagger

  • 号称世界上最流行的Api框架
  • Restful Api 文档在线生成工具 => Api文档与Api定义同步更新
  • 直接运行可以测试Api接口
  • 支持多种语言
    swagger官网

在项目中使用Swagger需要springfox

  • swagger2
  • swagger-ui

SpringBoot集成Swagger

1.新建一个springboot-web项目
2.引入jar包

  • maven官网下载

SPringBoot整合Swagger2_第1张图片

  • pom.xml文件引入
		
            io.springfox
            springfox-swagger2
            2.9.2
        

        
            io.springfox
            springfox-swagger-ui
            2.9.2
        

3.编写一个Hello工程

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello(){
        return "hello swagger";
    }

}

4.集成Swagger --> Config
在config目录下新建一个SwaggerConfig文件
进行swagger配置

@Configuration
@EnableSwagger2 //开启swagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {

}

5.测试运行:
访问页面(端口写自己的)
localhost:8089/swagger-ui.html
SPringBoot整合Swagger2_第2张图片

配置Swagger

Swagger的bean实例Docket;
下面是我自定义配置的swagger:

@Configuration
@EnableSwagger2 //开启swagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    //配置swagger的学生Docket的bean实例
    @Bean
    public Docket studentDocket(Environment environment){

        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("admin")
                .apiInfo(apiInfo())
                .select()
                //RequestHandlerSelectors配置要扫描接口的方式
                //basePackage指定要扫描的包
                .apis(RequestHandlerSelectors.basePackage("org.graduation.financialmanagement.controller"))
                .build();
    }

    //配置swagger信息
    private ApiInfo apiInfo(){
        //作者信息
        Contact contact = new Contact("Alisa", "", "2868714995@qq.com");
        return new ApiInfo(
                "financial management project API Documentation",
                "financial management project Api Documentation",
                "v1.0",
                "http://localhost:8088",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList());
    }

}

你可能感兴趣的:(学习笔记)