Springboot集成Swagger2(亲测直接可用)

1:在springboot启动类配置如下,方便启动项目直接看到路径,点击可直接测试

@Slf4j
@SpringBootApplication
public class SpbthymyibatisApplication {

    public static void main(String[] args) throws UnknownHostException {
        ConfigurableApplicationContext application =SpringApplication.run(SpbthymyibatisApplication.class, args);
        Environment env = application.getEnvironment();
        String ip = InetAddress.getLocalHost().getHostAddress();
        String port = env.getProperty("server.port");
        String path = env.getProperty("server.servlet.context-path");
        log.info("\n----------------------------------------------------------\n\t" +
                "Application Jeecg-Boot is running! Access URLs:\n\t" +
                "Local: \t\thttp://localhost:" + port + path + "/\n\t" +
                "External: \thttp://" + ip + ":" + port + path + "/\n\t" +
                "swagger-ui: \thttp://" + ip + ":" + port + path + "/swagger-ui.html\n\t" +
                "Doc: \t\thttp://" + ip + ":" + port + path + "/doc.html\n" +
                "----------------------------------------------------------");
    }

}

2:Swagger配置类

package com.example.config;

import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author dell
 * @create 2022/11/8
 */
@Slf4j
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    /**
     * swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
     *
     * @return Docket
     */
    @Bean
    public Docket createRestApi() {
        ParameterBuilder tokenPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<>();
        tokenPar.name("X-Access-Token").description("AccessToken令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        pars.add(tokenPar.build());
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //扫描方式1,此包路径下的类,才生成接口文档
                .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                //扫描方式2:扫描所有有类注解的api,加了Api注解的类,才生成接口文档
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                //扫描方式3:扫描所有有方法注解的ApiOperation,用这种方式更灵活,才生成接口文档
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                // 扫描方式4:扫描所有
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(pars);
    }

    /**
     * api文档的详细信息函数,注意这里的注解引用的是哪个
     *
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spbthymyibatis 后台服务API接口文档")
                .description("restful 风格接口")
                .termsOfServiceUrl("http://www.baidu.com/")
                .version("1.0")
                .build();
    }
}

2:在yaml或者properties文件配置

server.port=8888
server.servlet.context-path=/spbthymeibatis
#注意必须要有此行ant匹配,不然swagger启动报错
spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER
#扫描实体类
mybatis.type-aliases-package=com.example.entity
#扫描映射文件
mybatis.mapper-locations: classpath:mapper/*.xml

#配置数据库
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false&autoReconnect=true&failOverReadOnly=false&autoReconnectForPools=true
spring.datasource.username=root
spring.datasource.password=root

#过滤静态资源
spring.mvc.static-path-pattern=/**

#指定系统直接访问路径
spring.web.resources.static-locations = classpath:/templates/,classpath:/META-INF/resources/,classpath:/resources/
#热部署:修改后台文件保存后自动重启
#spring.devtools.restart.enabled=true

#Messages资源信息
#spring.messages.basename=messages

#关闭thymeleaf缓存 开发时使用 否则没有实时画面
spring.thymeleaf.cache=false

3:pom配置


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.6.1version>
        <relativePath/> 
    parent>
    <groupId>com.examplegroupId>
    <artifactId>spbthymyibatisartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <packaging>warpackaging>

    <name>spbthymyibatisname>
    <description>Demo project for Spring Bootdescription>
    <properties>
        <java.version>1.8java.version>
    properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.2.0version>
        dependency>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        
        
        <dependency>
            <groupId>io.swaggergroupId>
            <artifactId>swagger-annotationsartifactId>
            <version>1.5.21version>
        dependency>
        <dependency>
            <groupId>io.swaggergroupId>
            <artifactId>swagger-modelsartifactId>
            <version>1.5.21version>
        dependency>
        
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger2artifactId>
            <version>2.9.2version>
        dependency>
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger-uiartifactId>
            <version>2.9.2version>
        dependency>
        <dependency>
            <groupId>com.github.xiaoymingroupId>
            <artifactId>swagger-bootstrap-uiartifactId>
            <version>1.9.3version>
        dependency>
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-bean-validatorsartifactId>
            <version>2.9.2version>
        dependency>

        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>


    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-resources-pluginartifactId>
                <version>3.1.0version>
            plugin>
        plugins>
    build>

project>

4:将接口文档暴露在外网会出现一定的安全问题,此时我们需要给Swagger文档配置登录密码

4-1:添加依赖,已经添加过

<dependency>
    <groupId>com.github.xiaoymingroupId>
    <artifactId>swagger-bootstrap-uiartifactId>
    <version>1.9.3version>
dependency>

4-2:更新配置类,再配置类加上@EnableSwaggerBootstrapUI

@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI 	//添加注解
public class SwaggerConfig {
}

4-3:在yaml或者properties文件添加

# true为启动用密码,false为关闭密码
swagger.basic.enable=true
swagger.basic.username=admin
swagger.basic.password=admin

5:Swagger常用注解

//控制类上
@Api(tags = “控制类”)

//控制类的方法上
@ApiOperation(value = “方法”, notes = “方法”)

//控制类方法参数上使用
@ApiParam(value = “参数”, allowableValues = “range[1,10]”, required = true)

//控制类方法上这是请求的@ApiImplicitParams、@ApiImplicitParam
@ApiImplicitParams({
@ApiImplicitParam(name=“phonenum”,value=“手机号”,required=true,paramType=“form”),
@ApiImplicitParam(name=“password”,value=“密码”,required=true,paramType=“form”),
@ApiImplicitParam(name=“age”,value=“年龄”,required=true,paramType=“form”,dataType=“Integer”)
})

//控制类方法上这是响应的@ApiResponses、@ApiResponse
@ApiResponses({
@ApiResponse(code = 200, message = “请求成功”),
@ApiResponse(code = 400, message = “请求参数没填好”),
@ApiResponse(code = 404, message = “请求路径没有或页面跳转路径不对”)
})

//实体类,dot,vo,entity上
@ApiModel(value=“对象”, description=“对象”)

//实体类,dot,vo,entity的属性上
@ApiModelProperty(value = “属性”)

注意:yaml或者properties配置文件里面的空格和缩进都要特别注意,不能有多余,不然识别不出来

你可能感兴趣的:(spring,boot,java,spring)