java日常开发笔记

Springboot整合Swagger2实现项目的api工具

2020-01-19  本文已影响0人  毁于一蛋

1、pom文件

        <swagger.version>2.9.2</swagger.version>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
        </dependency>

2、配置SwaggerConfig

最好将这个类放置于项目的启动主函数同一个目录下。(但是我没放,没发现什么问题,后面出现问题再做补充)

package com.im;

import org.springframework.context.annotation.*;
import springfox.documentation.builders.*;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * create by wuxuan.chai
 * at 2019/11/1 3:59 下午
 *
 * @since 0.0.0.1-SNAPSHOT
 **/
@EnableSwagger2
@Configuration
@Profile({"test","dev"})
public class SwaggerConfig {

    @Bean
    public Docket createUserDocket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("user")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.im.system.user.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("Spring Boot Swagger2 构建RESTFUL API")
                .version("0.0.0.1-SNAPSHOT")
                .license("2019-11-01")
                .description("IM-API 描述")
                .build();
    }
}

3、配置Swagger-ui.html的请求配置

package com.im.common.http;

import com.google.common.base.Charsets;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.*;

import java.util.List;

/**
 * create by wuxuan.chai
 * at 2019/10/29 11:07 下午
 *
 * @since 0.0.0.1-SNAPSHOT
 **/

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    
    @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/");
    }
}

4、如果开启关闭Swagger

在application.properties里面配置

# dev:开发环境(开启)  test:测试环境(开启)  xxx:其他(关闭)
spring.profiles.active=dev 

5、访问swagger

http://域名/根路径/swagger-ui.html

6、使用swagger的api文档


swagger2实战

上一篇 下一篇

猜你喜欢

热点阅读